简体   繁体   English

使用实体框架读取复杂/相关数据

[英]Reading complex/related data using Entity Framework

I want to read (using EF) City and Country information like CityID, CityName, CountryID, CountryName from the tables City and Country, which has appropriate FK relation. 我想从表City and Country中读取(使用EF)City和Country信息,例如CityID,CityName,CountryID,CountryName,它们具有适当的FK关系。

For this, I can use 为此,我可以使用

  1. from x in db.Cities.Include("Country") select x - This results in complex query which tries to read all unwanted columns from x in db.Cities.Include("Country") select x这将导致复杂的查询,该查询尝试读取所有不需要的列

  2. from x in db.Cities join y in db.Countries on x.CountryID equals y.CountryID select new CityDTO{ x.CityID, x.CityName, y.CountryID, y.CountryName} - This results in creating lots of DTO classes and transformations. from x in db.Cities join y in db.Countries on x.CountryID equals y.CountryID select new CityDTO{ x.CityID, x.CityName, y.CountryID, y.CountryName} -这将导致创建许多DTO类和转变。

  3. from x in db.CityView select x - this results in creating many views and whenever I want to get additional column, I need to update the edmx. from x in db.CityView select x这将导致创建许多视图,并且每当我想要获得更多列时,都需要更新edmx。

  4. Create additional property called CountryName in City class 在城市类中创建名为CountryName其他属性

and use 和使用

from x in db.Cities select x
foreach (var city in x)
  city.CountryName = (from y  in db.Countries where ...)

*** This is because EF is not allowing me to create City object inside the query otherwise I would have used from x in db.Cities join y in db.Countries select new City{x.CityID, x.CountryID, x.CityName, y.CountryName} ***这是因为EF不允许我在查询中创建City对象,否则我会from x in db.Cities join y in db.Countries select new City{x.CityID, x.CountryID, x.CityName, y.CountryName}

What is the best way to go in this case (with less entities and performing query)? 在这种情况下(实体较少且执行查询的情况)的最佳方式是什么?

How about 怎么样

from x in db.Cities.Include("Country") 
select new { x.CityID, x.CityName, x.Country.CountryID, x.Country.CountryName }

This selects just the specified fields into an anon type, allowing you to select only cols you care about 这仅将指定的字段选择为匿名类型,从而允许您仅选择自己关心的列

To use an existing entity you can use a similar syntax, eg. 要使用现有实体,可以使用类似的语法,例如。

from x in db.Cities.Include("Country") 
select new City { 
         CityID = x.CityID, 
         CityName = x.CityName, 
         Country = new Country{ 
                       CountryID = x.Country.CountryID, 
                       CountryName = x.Country.CountryName 
                   } 
         }

If you look at the generated SQL for either of these expressions you will see that its only selecting the mentioned columns. 如果查看为这两个表达式生成的SQL,您将看到它仅选择了提到的列。

Do be aware however that the entity returned from both of these queries is not tracked, so you cant use it directly to perform an update. 但是请注意,不会跟踪从这两个查询返回的实体,因此您不能直接使用它来执行更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM