Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework select single value from row

I am using Entity Framework from .NET 3.5

I have two tables with 0-1 to many relation. Let's say Citizen and City. Each citizen has foreign key column (ID) that connects him to City.

When i select single citizen, i also need to select the name of the city where he lives. Because city table contains tons of data that is not really related to citizen, so i don't want to retrieve it from database to save some bandwidth.

Currently i am using Include() function, but it grabs all the data from the City related to citizen, while i need only name.

Is there a way to write a query to select single cell from the whole row in EF and without creating new classes or interfaces or repositories? Here is my Include:

            Citizen citizen = db.Citizens.Include("Cities").First(p => p.citizen_id == id);
like image 425
Alex Avatar asked Jun 17 '26 19:06

Alex


1 Answers

You do this by projecting, e.g.

var c = from c in db.Citizens
        where c.citizen_id == id
        select new
        {
            Name = c.Name,
            CityName = c.City.Name
        };

You can also project onto POCOs.

You cannot tell the EF to retrieve an object of type Citizen with a related City but with only City.Name filled in. The EF will not partially materialize an entity. Use view / presentation models or DTOs instead of entities when you need only a few fields.

like image 192
Craig Stuntz Avatar answered Jun 19 '26 07:06

Craig Stuntz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!