不能访问LINQ中的左联接实体
本文关键字:实体 访问 LINQ 不能 | 更新日期: 2023-09-27 17:53:30
我正在LINQ中执行左连接,我遇到了一个问题。我的问题是,我在我的where子句中对两个表进行比较,但我实际上无法访问"cat"表。如何访问左联接中的表呢?
var query = from apple in Apple
join ball in Ball on apple.Id equals ball.AppleId
join cat in Cat on ball.Id equals cat.BallId into leftJoin
join dog in Dog on ball.Id equals dog.BallId
where apple.Id == 5
// At this point cat is not accessable. Cannot resolve symbol "cat".
where dog.CatName == cat.Name
from cat in leftJoin.DefaultIfEmpty()
select new
{
// select stuff here...
};
我不是100%确定,但试试这个:
var query = from apple in Apple
join ball in Ball on apple.Id equals ball.AppleId
join cat in Cat on ball.Id equals cat.BallId into leftJoin
from cat in leftJoin.DefaultIfEmpty()
join dog in Dog on ball.Id equals dog.BallId
where apple.Id == 5
where dog.CatName == cat.Name
select new
{
// select stuff here...
};
当然,如果你适当地设置了导航属性,它看起来就像这样:
var query = from apple in Apple
from ball in apple.Balls
from cat in ball.Cats.DefaultIfEmpty()
from dog in ball.Dogs
where apple.Id == 5
where dog.CatName == cat.Name
select new
{
// select stuff here...
};
问题是您选择了多个猫到LeftJoin…这使得它是一个IEnumerable,所以没有单一的猫,所以查询并不完全有意义…你想检查狗是否和猫匹配吗?
我已经把你的leftJoin
重命名为catsForThisBall
,使它更清晰。
var query = from apple in Apple
join ball in Ball on apple.Id equals ball.AppleId
join cat in Cat on ball.Id equals cat.BallId into catsForThisBall
join dog in Dog on ball.Id equals dog.BallId
where apple.Id == 5
// catsForThisBall is IEnumerable<Cat>... cat doesn't exist.
where catsForThisBall.Any(c => c.name == dog.name)
select new
{
// select stuff here...
};