zoukankan      html  css  js  c++  java
  • Linq NOT IN (或 NOT EXISTS)、LEFT JOIN踩坑记

    原先项目中有SQL语句NOT IN,把它改造成Linq

    var b = from e in YY
            where !(
                from c in XX
                where c.XXId == 123
                select c.XXId
            ).Contains(e.YYId)

    网上搜到的都是这种方法,在子查询后Contains判断是否包含

    如果是NOT EXISTS,也可以用 .Any(m=>...)

    看上去很简单没什么问题,测试时发现报错,【此上下文仅支持基元类型或枚举类型】,反复检查测试,花了半上午。。。

    后来发现这种写法只支持一个实体,如果是多个实体,要分开写。(应该是EF中映射实体才有这问题,普通linq应该是可以的)

    var a = from c in XX
            where c.XXId == 123
            select c.XXId;
            
    var b = from e in YY
            where !a.Contains(e.YYId)

    中文网上都没有提到这码事,只在stackoverflow上找到一篇,就是说的这个问题

    http://stackoverflow.com/questions/16836516/error-message-only-primitive-types-or-enumeration-types-are-supported-in-this

    ======================

    LEFT JOIN:

    Linq居然没有LEFT JOIN。。。就不能把SQL关键字统统做个对应么。。。

    from a in b
    left join c in d on a.xx equal c.xx
    into e
    from f in e.DefaultIfEmpty()
    select new {
        a.XX,
        YY = f==null? "" : f.YY
    }

    要使用into和DefaultIfEmpty,并且要在赋值时判断null

    RIGHT JOIN 同理

  • 相关阅读:
    UVA 10618 Tango Tango Insurrection
    UVA 10118 Free Candies
    HDU 1024 Max Sum Plus Plus
    POJ 1984 Navigation Nightmare
    CODEVS 3546 矩阵链乘法
    UVA 1625 Color Length
    UVA 1347 Tour
    UVA 437 The Tower of Babylon
    UVA 1622 Robot
    UVA127-"Accordian" Patience(模拟)
  • 原文地址:https://www.cnblogs.com/liuyouying/p/5190159.html
Copyright © 2011-2022 走看看