[英]Reading complex/related data using Entity Framework
我想从表City and Country中读取(使用EF)City和Country信息,例如CityID,CityName,CountryID,CountryName,它们具有适当的FK关系。
为此,我可以使用
from x in db.Cities.Include("Country") select x
这将导致复杂的查询,该查询尝试读取所有不需要的列
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类和转变。
from x in db.CityView select x
这将导致创建许多视图,并且每当我想要获得更多列时,都需要更新edmx。
在城市类中创建名为CountryName
其他属性
和使用
from x in db.Cities select x
foreach (var city in x)
city.CountryName = (from y in db.Countries where ...)
***这是因为EF不允许我在查询中创建City对象,否则我会from x in db.Cities join y in db.Countries select new City{x.CityID, x.CountryID, x.CityName, y.CountryName}
在这种情况下(实体较少且执行查询的情况)的最佳方式是什么?
怎么样
from x in db.Cities.Include("Country")
select new { x.CityID, x.CityName, x.Country.CountryID, x.Country.CountryName }
这仅将指定的字段选择为匿名类型,从而允许您仅选择自己关心的列
要使用现有实体,可以使用类似的语法,例如。
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
}
}
如果查看为这两个表达式生成的SQL,您将看到它仅选择了提到的列。
但是请注意,不会跟踪从这两个查询返回的实体,因此您不能直接使用它来执行更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.