Asp.net mvc 3 实体框架-复杂查询最佳实践

Asp.net mvc 3 实体框架-复杂查询最佳实践,asp.net-mvc-3,tsql,entity-framework-4.1,Asp.net Mvc 3,Tsql,Entity Framework 4.1,在多语言数据库中,我有以下表格: 区域和区域语言环境:区域包含纬度/经度/区域Id&区域语言环境包含Id/名称/描述/区域Id/文化Id Country和CountryLocale:Country包含纬度/经度/CountryId和CountryLocale包含Id/Name/Description/CountryId/CultureId 区域性:包含Id/Name/DisplayName 现在,我需要检索以下内容: AreaId/Name/Description/Longitude/Lat

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

  • 区域和区域语言环境:区域包含纬度/经度/区域Id&区域语言环境包含Id/名称/描述/区域Id/文化Id
  • Country和CountryLocale:Country包含纬度/经度/CountryId和CountryLocale包含Id/Name/Description/CountryId/CultureId
  • 区域性:包含Id/Name/DisplayName
现在,我需要检索以下内容:

AreaId/Name/Description/Longitude/Latitude/CountryId/Country Name/CultureId/culturedisplay Name,这样区域的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();

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

参考您的评论:


事实上,我有以下内容:地区、国家和地区的地区语言环境列表 区域实体上的属性,以及国家/地区上的CountryLocale列表

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

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

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时,实体框架将创建必要的连接。

您的模型中没有导航属性吗,例如
公共ICollection Area Locales{get;set;}
公共国家{get;set;}
中的
区域
类等?如果你有这些,你根本就不需要任何手写连接。事实上,我有以下内容:Area上的AreaLocales列表,Area实体上的country属性,以及country上的CountryLocale列表。如何实现上述目标?谢谢你令人印象深刻的回答。我正在努力理解上面的细节。上述查询将返回每个区域的区域列+区域语言环境集合。至于国家名称,每个地区都有一个国家,所以我假设国家名称将包括该地区所属的单个国家的所有地区,对吗?了解EF有什么好的资源,如何编写查询?谢谢还有一个问题,如果我想过滤掉基于国家和文化的数据,我会在AreaLocales中添加一个.Where(),在CountryName中添加一个?@bhaidar:是的,你在第一条评论中的理解是正确的。是的,您可以在第一个示例中添加一个
,其中
,以过滤子对象,但在第二个示例中(在
包含
的内部)不能添加,因为即时加载不允许过滤包含的属性。这里介绍了EF 4.1:非常感谢Slauma!谢谢。
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();