Entity Framework selects a single row value.

.net-3.5 c# entity-framework

Question

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);
1
3
6/4/2010 6:52:26 PM

Accepted Answer

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.

2
6/4/2010 7:21:36 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