Entity Framework getting data from the ENTIRE column

70 Views Asked by At

I've got an api call getUser which returns ALL the info from the database at the specified column, but I want to exclude some things; phonenumber, email etc.

Tried fiddling with the LINQ, changeing the modelBuilder, changeing the optionBuilder

Have looked for any SQL saying "Select * from" but found nothing

Deleting things in my UserModel do work, however this is an ugly way of doing it.

Result<UserModel> result = new Result<UserModel>();
try
    {
        using (var db = new ComeatDBContext(optionsBuilder.Options))
        {
            var user = db.User
                .Include(f => f.Nationality)
                .Include(f => f.State)
                .FirstOrDefault(e => e.Id == id && !e.IsDeleted);

            result.ResponseObject = (new UserModel()).FromUser(user);
            var house = db.House.FirstOrDefault(e => e.UserId == user.Id);
            if (house != null)
            {
                result.ResponseObject.House = ( new HouseModel() ).FromHouse(house);
            }
            result.Success = true;
        }

Expected specifying which data to include (or not include) but instead I get everything unless I set the values to "null" after they've been delievered by the DB.

1

There are 1 best solutions below

4
On BEST ANSWER

The .FirstOrDefault(...) is what causes the underlying database query (SQL) to be executed. It will populate all properties that are defined on the entity. The data entity is then transformed to your UserModel object when you execute (new UserModel()).FromUser(user);.

If you want to reuse your UserModel class but not populate all the columns you can do something like this;

var userModel = db.User
     .Select(x => new UserModel { Name = x.Name, Id = x.Id })
     .FirstOrDefault(e => e.Id == id && !e.IsDeleted);

result.ResponseObject = userModel;