在多语言数据库中,我有以下表格:
现在,我需要的是检索以下内容:
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?
答案 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时创建必要的连接。