根据LINQ中的Where条件使少数列为NULL

时间:2015-03-09 20:12:05

标签: c# sql-server linq

我正在开发一个C#应用程序,我从SQL数据中返回一个完整的数据,这些数据可以用以下数据解释

表1

Id Term Location Bvol  Buser Bid Offer Ovol Ouser
1   Q1   Hou     100   dev   10   20   200   john
2   Q2   Hou     50    john  25   40   100   dev
3   Q2   Bea     1000  dev   30   45   2000  dev

我正在尝试检索与名为dev的用户相关的所有数据,我正在将devBuserOuser进行比较,我正在尝试返回{ {1}}至少有一个Id Term and Location与用户Buser and Ouser匹配,但如果用户devdev但不是Buser匹配,我只返回{如果与Ouser匹配,则{1}}和Bvol,Bid,Buser以及Id, Term and Location同样适用。

预期结果如下

Offer,Ovol and Ouser as NULL

首先,如果Ouser

中有匹配项,则在返回整行时使用了以下查询
 Id Term Location    Bvol    Buser   Bid Offer Ovol Ouser
    1   Q1   Hou     100      dev    10   NUll NULL NULL
    2   Q2   Hou     NULL    NULL    NUll 40   100   dev
    3   Q2   Bea     1000     dev    30   45   2000  dev

我是否知道实现早期指定要求的好方法?

2 个答案:

答案 0 :(得分:1)

它可能适用于联盟:

有些事情:

      var bids = db.BrokerOutrights
            .Where(b => b.BidBroker == 'dev')
            .Select(b => new { Id = b.Id, Term = b.Term, Location = b.Location, Bvol = b.Bvol, Buser = b.Buser, Bid = b.Bid, Offer = (int?)null, Ovol = (int?)null, Ouser = (string)null });

        var offers = db.BrokerOutrights
            .Where(b => b.OfferBroker == 'dev')
            .Select(b => new { Id = b.Id, Term = b.Term, Location = b.Location, Bvol = (int?)null, Buser = (string)null, Bid = (int?)null, Offer = b.Offer, Ovol = b.Ovol, Ouser = b.Ouser });

        return bids.Union(offers).Select(x => new BrokerOutright { Id = x.Id .... }).ToList();

想法是创建两个投射到匿名类型的查询;其中两个匿名类型具有相同的签名,因此可以联合。

然后,您需要将联合查询投影回实体(BrokerOutright)并将集合ToList以运行查询。

答案 1 :(得分:0)

原则很简单,你必须成长

select (x == 'dev') ? value : null;

这可以针对每一列进行

db.BrokerOutrights.Where(b => b.Buser == 'dev'|| b.Ouser=='dev')
.Select(i => new 
{
    i.Id, 
    i.Term, 
    i.Location, 
    (i.Buser == 'dev') ? i.Bvol : null, 
    (i.Buser == 'dev') ? i.Buser : null, 
    (i.Buser == 'dev') ? i.Bid: null, 
    (i.Ouser == 'dev') ? i.Offer : null, 
    (i.Ouser == 'dev') ? i.Ovol : null, 
    (i.Ouser == 'dev') ? i.Ouser : null
};