views:

123

answers:

1

Hi all. 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);
A: 

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.

Craig Stuntz
Thank you, this is what i was looking for.Is there a way to get a cityName from var c right away? Lets say i am not using view models for that?
Sasha
You mean like `var cityName = c.First().CityName;` ?
Craig Stuntz