【问题标题】:Cannot Access Left Joined Entity In LINQ无法在 LINQ 中访问左连接实体
【发布时间】:2014-05-03 23:47:49
【问题描述】:

我正在 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...
            };

【问题讨论】:

    标签: c# sql linq tsql


    【解决方案1】:

    我不是 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...
                };
    

    【讨论】:

    • 那行得通。我需要在 where 子句之前使用 DefaultIfEmpty() 方法。谢谢!
    【解决方案2】:

    问题是您已将多只猫选择到 LeftJoin... 这使其成为 IEnumerable 因此没有单个猫因此查询不完全有意义...您是否要检查 dog 是否匹配任何加入的猫?

    我已将您的 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...
                };
    

    【讨论】:

      猜你喜欢
      • 2010-12-03
      • 2013-10-21
      • 2015-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多