我正在尝试转换以下SQL:
select * from business
left outer join permissions on permissions.permid = busid
and anotherid = 17
转换为C#lambda表达式,然后将其转换为可枚举,并对其执行另一个过滤器。我尝试了以下代码:
IEnumerable<DTO_business> business= db.business
.Join(db.permissions,
bus => bus.busid,
perm => perm.perm_busid,
(bus, perm) => new { bus, perm })
.Where(e => e.perm.anotherid == 17).DefaultIfEmpty()
.AsEnumerable()
.Where(User.IsInRole("Administrator")
.Select(bus =>
new DTO_business()
{
BusinessID = bus.bus.busid.Convert(),
BusinessName = bus.bus.busname.Convert()
});
但是我相信它没有工作,因为在加入之外的地方。我不确定如何在连接中实际获取,然后在连接上运行DefaultIfEmpty(),这应该给我左连接。
编辑:我无法工作的是:和另一个= 17 。如果我将它放在linq中的.Where中,它会完全过滤它,而不是左连接的一部分。
答案 0 :(得分:1)
对于我LINQ join
子句,查询语法总是很简单。如果您愿意,可以这样做: -
var result = from permission in db.permissions
join business in db.business
on permission.permid equals business.busid into b
from bus in b.DefaultIfEmpty()
where permission.anotherid == 17
select new DTO_business()
{
BusinessID = bus != null ? bus.busid : 0,
BusinessName = bus != null ? bus.busname : String.Empty
};
答案 1 :(得分:1)
查询语法会更容易,但您可以使用GroupJoin这样做:
var business= db.business
.GroupJoin(
db.permissions,
bus => bus.busid,
perm => perm.perm_busid,
(bus, perm) => new { bus, perm })
.SelectMany(
z => z.permissions.DefaultIfEmpty(),
(x, y) => new { Business = x.Bus, Permission = y })
.Where(z => z.Permission.anotherid == 17)
.Select(s => new DTO_business
{
BusinessID = s.Business.busid.Convert(),
BusinessName = s.Business.busname.Convert()
});
答案 2 :(得分:0)
您可以在连接条件中使用复合键。
from p in db.permissions
join b in db.business
on new { BusId = b.busid, AnotherId= b.anotherId}
equals new { BusId = p.perm_busid, AnotherId = 17 } into all
from b in all.DefaultIfEmpty()
select new DTO_business
{
BusinessID = b.busid, // check for null reference
BusinessName = b.busname // check for null reference
};
您也可以在扩展语法中类似地使用复合键。
我在您的代码中看到您在select函数中使用Convert
。 Linq中不允许转换为Sql。