实体框架 - 复杂查询最佳实践

时间:2012-03-23 11:49:56

标签: asp.net-mvc-3 tsql entity-framework-4.1

在多语言数据库中,我有以下表格:

  • 区域& AreaLocale:Area包含Latitude / Longitude / AreaId& AreaLocale包含Id / Name / Description / AreaId / CultureId
  • 国家& CountryLocale:国家/地区包含纬度/经度/ CountryId& CountryLocale包含Id / Name / Description / CountryId / CultureId
  • Culture:包含Id / Name / DisplayName

现在,我需要的是检索以下内容:

AreaId / Name / Description / Longitude / Latitude / CountryId / Country Name / CultureId / Culture显示名称,区域IsDeleted = false。

编写以下查询:

var q = (from areas in context.Areas
 join countries in context.Countries on areas.CountryId equals countries.CountryId
 join arealocales in context.AreaLocales on areas.AreaId equals arealocales.AreaId
 join cultures in context.Cultures on arealocales.CultureId equals cultures.CultureId
 join countrylocales in context.CountryLocales on areas.CountryId equals countrylocales.CountryId
 where areas.IsDeleted == false
 select new Area()
 {
      CountryId = areas.CountryId,
      CountryName = countrylocales.Name,
      CultureId = cultures.CultureId,
      CultureDisplayName = cultures.DisplayName,
                          Description = arealocales.Description,
      Id = areas.AreaId,
      Latitude = areas.Latitude,
      Longitude = areas.Longitude,
      Name = arealocales.Name
 }).ToList();

有没有更好的方法来编写上述查询而不是使用Joins而是使用UnionAll?

1 个答案:

答案 0 :(得分:1)

参考您的评论:

  

事实上,我有以下内容:Area,country上的AreaLocales列表   区域实体上的属性,以及国家/地区的CountryLocale列表。

我还假设AreaLocale有一个Culture属性(因为你在CultureId类上显然有一个AreaLocale属性):

var q = (from area in context.Areas
         where area.IsDeleted == false
         select new   // or: select new SomeHelperClass
         {
             Id = area.AreaId,
             Latitude = area.Latitude,
             Longitude = area.Longitude,
             CountryId = area.CountryId,

             AreaLocales = area.AreaLocales.Select(areaLocale => new
             {
                 Description = areaLocale.Description,
                 Name = areaLocale.Name,
                 CultureId = areaLocale.Culture.CultureId,
                 CultureDisplayName = areaLocale.Culture.DisplayName
             }),

             CountryNames = area.Country.Countrylocales.Select(
                 countryLocale => countryLocale.Name)
         })
        .ToList();

结果对象有两个嵌套列表,四个是AreaLocales和CountryNames。如果这些几乎都是类的所有属性,那么你也可以使用预先加载:

var q = (from area in context.Areas
             .Include(a => a.AreaLocales.Select(al => al.Culture))
             .Include(a => a.Country.CountryLocales)
         where area.IsDeleted == false
         select area)
        .ToList();

实体框架将在将这些LINQ查询转换为SQL时创建必要的连接。