Entity Framework selects a single value from a string

I am using Entity Framework from .NET 3.5

I have two tables with a ratio from 0-1 to many. Say a citizen and a city. Each citizen has a foreign key (ID) column that connects it to the city.

When I choose one citizen, I also need to choose the name of the city in which he lives. Since the city table contains tons of data that are not really related to citizens, so I don’t want to extract them from the database in order to save some bandwidth.

I am currently using the Include () function, but it captures all data from the City related to citizens, while I only need a name.

Is there a way to write a query to select a single cell from the entire 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);
+3
source share
1 answer

You do this by projecting, for example.

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

You can also complete the project on POCOs.

You cannot tell EF to get an object of type Citizenwith the appropriate City, but only with padding only City.Name. EF does not partially materialize the object. Use presentation / presentation or DTO models instead of objects when you need only a few fields.

+2
source

Source: https://habr.com/ru/post/1748582/


All Articles