左连接的 Linq 查询
Linq query for left-join
我有 3 个表:
* UserSettingsType { general, UserSpecific)
* UserSettingsOption { Currency:general, Language:general, Location:Userspecific }
* UserSettingsValue { Currency:USD, Location:US }
如果我 运行 SQL
查询:
select ust.Name Type, uso.Name Option, usv.Value Value from UserSettingOption uso
inner join UserSettingType ust on ust.Id = uso.Type_Id
left join UserSettingValue usv on usv.Setting_Type_Id = uso.Id
输出为:
Type | Name | Value
--------------------------------
General | Currency | USD
General | Language | NULL
UserSpecific | Location | US
如何将以上内容转换为 Linq
格式?
我是这样想的
var item=(from a in contex.usersettingoption
from b in contex.usersettingtype.where(x=>x.id==a.Type_id).DefaultIfEmpty()
from c in contex.usersettingvalue.where(x=>x.setting_Type_Id==a.id).DefaultIfEmpty()
select new {b.Type,a.Name,c.value}).ToList()
您可以执行以下操作:
var result = (form uso in Context.UserSettingOption
join ust in Context.UserSettingType on uso.Type_Id equals ust.Id
join usv in Context.UserSettingValue on uso.Id equals usv.Setting_Type_Id into tmpusv
from lusv in tmpusv.DefaultIfEmpty()
select new
{
Type = ust.Name,
Option = uso.Name,
Value = lusv != null ? lusv.Value : null
}).ToList();
我有 3 个表:
* UserSettingsType { general, UserSpecific)
* UserSettingsOption { Currency:general, Language:general, Location:Userspecific }
* UserSettingsValue { Currency:USD, Location:US }
如果我 运行 SQL
查询:
select ust.Name Type, uso.Name Option, usv.Value Value from UserSettingOption uso
inner join UserSettingType ust on ust.Id = uso.Type_Id
left join UserSettingValue usv on usv.Setting_Type_Id = uso.Id
输出为:
Type | Name | Value
--------------------------------
General | Currency | USD
General | Language | NULL
UserSpecific | Location | US
如何将以上内容转换为 Linq
格式?
我是这样想的
var item=(from a in contex.usersettingoption
from b in contex.usersettingtype.where(x=>x.id==a.Type_id).DefaultIfEmpty()
from c in contex.usersettingvalue.where(x=>x.setting_Type_Id==a.id).DefaultIfEmpty()
select new {b.Type,a.Name,c.value}).ToList()
您可以执行以下操作:
var result = (form uso in Context.UserSettingOption
join ust in Context.UserSettingType on uso.Type_Id equals ust.Id
join usv in Context.UserSettingValue on uso.Id equals usv.Setting_Type_Id into tmpusv
from lusv in tmpusv.DefaultIfEmpty()
select new
{
Type = ust.Name,
Option = uso.Name,
Value = lusv != null ? lusv.Value : null
}).ToList();