我有以下代码:
public SiteViewModel SVMGetByID(int siteID)
{
SiteViewModel siteViewModel = (
from site in context.Sites
join address in context.Addresses on site.AddressID equals address.AddressID
//join city in context.Cities on address.CityID equals city.CityID
join country in context.Countries on address.CountryID equals country.CountryID // This needs to be a left join I think?
join state in context.States on address.StateID equals state.StateID // This needs to be a left join I think?
where site.SiteID == siteID
select new SiteViewModel
{
SiteID = site.SiteID,
Name = site.Name,
AddressID = address.AddressID,
Address1 = address.Address1,
Address2 = address.Address2,
City = address.City,
State = state,
StateID = state.StateID,
Country = country,
CountryID = country.CountryID,
ZIP = address.ZIP
}
).FirstOrDefault();
// If address.CityID and address.StateID have a value the siteViewModel is correctly filled,
// otherwise it is not.
return siteViewModel;
}
如果在我的数据库中,我的地址表包含address.CityID
或address.StateID
的空条目,则返回空结果...我实际上希望它返回结果,无论是否加入失败与否(左连接?)。
这两列用“允许空值”勾选...我的地址模型也表示Nullable<int>
... 是否应该是其他的连接词?
答案 0 :(得分:0)
您可以使用group join
。查看this documentation。
来自那里的例子:
var innerGroupJoinQuery =
from category in categories
join prod in products on category.ID equals prod.CategoryID into prodGroup
select new { CategoryName = category.Name, Products = prodGroup };
答案 1 :(得分:0)
您使用...然后从下面执行以将其加入原始查询。
SiteViewModel siteViewModel = (
from site in context.Sites
join address in context.Addresses on site.AddressID equals address.AddressID
join country in context.Countries on address.CountryID equals country.CountryID into joinedCountry
from country in joinedCountry.DefaultIfEmpty()
join state in context.States on address.StateID equals state.StateID into joinedState
from state in joinedState.DefaultIfEmpty()
where site.SiteID == siteID
select new SiteViewModel
{
SiteID = site.SiteID,
Name = site.Name,
AddressID = address.AddressID,
Address1 = address.Address1,
Address2 = address.Address2,
City = address.City,
//CityID = city.CityID,
State = state,
StateID = state.StateID,
Country = country,
CountryID = country.CountryID,
ZIP = address.ZIP
}
).FirstOrDefault();
return siteViewModel;