Get all columns except one in EFCore

.net-core entity-framework-core

Question

I have a users table in my database that includes username, encrypted password, email and role id. I would like to pull back a list of all users excluding the password.

Through searching I have found answers for ef 6 and below but nothing that works in ef core.

This is what I have currently:

using (var context = new dbcontext())
{
     return context.Users.ToList()
}

I have tried

using (var context = new dbcontext())
{
     return context.Users
     .Select (u => new
     {
           Id = u.Id
           Username = u.Username
           Email = u.Email
      }
     .ToList()
}

Doing this returns nothing.

I have tried mapping a new entity and class to the table leaving out the password column but nothing gets returned. I think possibly because it's a required field.

Currently I am just converting the response to a new UserSummary class that doesn't have the password property but I'd think there is a way to do this without the password being returned at all.

1
2
7/3/2017 3:39:24 AM

Popular Answer

You can create a class with the properties that you want to use ex:

origing class:

public class Rating
{
    public Rating() { }
    public int IdRating { get; private set; }
    public string IdUser { get; set; }
    public decimal Value { get; private set; }
    public string Comment { get; private set; }
    public bool IsEnabled { get; set; }
    public int IdCorrespondent { get; private set; }}

Destination class:

public class RatingView
{
    public Rating() { }
    public int IdRating { get; private set; }
    public decimal Value { get; private set; }
}

And map it on the repository with the method select ex:

public List<RatingView> ListRatings()
    {
        return _context.Ratings.Select(x => new RatingView
        {
            IdRating = x.IdRating ,
            Value = x.Value ,
        }).ToList();

    }

if you don't want to remodel the class u can make your own query using dapper, and u can find interesting things about dapper way here

1
6/1/2018 7:06:49 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow