我们公司正在转向实体框架,它与我们的旧系统有很大不同,所以我们有点迷失。
在这种情况下,我们需要一个左连接。我可以确认我应该返回1行我需要的结果,但我似乎无法编写连接查询以成功拉出任何行。它只显示返回0行。
我们尝试了3种不同的方法,每次都失败了。我觉得我们很接近,但似乎无法让它发挥作用。
1)此方法不会抛出异常,但会返回0结果。
var joinedHistoricalData = from loc in locationQuery
join hd in historicalData on loc.LocationFieldLocId equals hd.LocationId
select new HistoricalDataViewModel
{
Id = hd.Id,
LocId = (loc.LocationFieldLocId == null ? 0: (int)loc.LocationFieldLocId) ,
DivisionId = (loc.LocationFieldDivisionId == null ? 0 : (int)loc.LocationFieldDivisionId),
LocationPartName = loc.LocationFieldName,
LocationPartAddress1 = loc.LocationFieldAddressLine1,
LocationPartAddress2 = loc.LocationFieldAddressLine2,
LocationPartDescription = loc.LocationFieldDescription,
Entries = hd.Entries,
ModifiedDate = hd.ModifiedDate ,
ModifiedBy = String.Empty
};
2)按照指南我们稍微更改了一下查询以添加DefaultIfEmpty()方法。也返回0结果。
var joinedHistoricalData = from loc in locationQuery
join hd in historicalData on loc.LocationFieldLocId equals hd.LocationId into hdTemp
from hdSub in hdTemp.DefaultIfEmpty()
select new HistoricalDataViewModel
{
Id = hdSub .Id,
LocId = (loc.LocationFieldLocId == null ? 0: (int)loc.LocationFieldLocId) ,
DivisionId = (loc.LocationFieldDivisionId == null ? 0 : (int)loc.LocationFieldDivisionId),
LocationPartName = loc.LocationFieldName,
LocationPartAddress1 = loc.LocationFieldAddressLine1,
LocationPartAddress2 = loc.LocationFieldAddressLine2,
LocationPartDescription = loc.LocationFieldDescription,
Entries = hdSub .Entries,
ModifiedDate = hdSub .ModifiedDate ,
ModifiedBy = String.Empty
};
3)另一个指南提到我们应该指定左连接空对象,所以在DefaultIfEmpty()方法中我们将它添加为一个参数,它完全崩溃说LINQ无法创建实体框架复杂对象。
new ef_HistoricalData{Id = 0,
Entries= 0,
DivisionId = (loc.LocationFieldDivisionId == null ? 0 : (int)loc.LocationFieldDivisionId),
LocId = (loc.LocationFieldLocId == null ? 0 : (int)loc.LocationFieldLocId),
ModifiedById = null,
ModifiedDate = DateTime.UtcNow
}
我不知道该怎么做。 我在做一个Leftjoin错了吗?
*注意,这里需要完整或左连接,右边或内部将返回0结果我相信)