Entity Framework selects a single row value.

.net-3.5 c# entity-framework

Question

Entity Framework from.NET 3.5 is what I'm using.

I have two tables that are connected 0-1 to many. Say the words Citizen and City. Each citizen is linked to the city through a foreign key column (ID).

I must additionally choose the city where he resides when I choose single citizen. In order to conserve some bandwidth, I don't want to fetch the data from the database since the city table includes a ton of information that is not actually linked to the citizens.

I now use the Include() method, however it pulls all the citizen-related data from the City when I just need the name.

Is it possible to build a query in EF that selects a single cell from the whole row without adding any additional classes, interfaces, or repositories? This is what I include:

            Citizen citizen = db.Citizens.Include("Cities").First(p => p.citizen_id == id);
1
3
6/4/2010 6:52:26 PM

Accepted Answer

To achieve this, project, for example.

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

Onto POCOs may also be projected.

You instruct the EF to fetch an item of type with cannot.Citizen with a connectedCity but only withCity.Name stuffed in. An entity cannot be partly materialized by the EF. When you simply require a few fields, avoid using entities and instead use view/presentation models or DTOs.

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