C# 左连接的Linq查询
我有三张桌子:C# 左连接的Linq查询,c#,sql,linq,sql-to-linq-conversion,C#,Sql,Linq,Sql To Linq Conversion,我有三张桌子: * 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 Val
* 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();