如何在实体上写入查询

时间:2019-02-12 01:01:08

标签: c# entity-framework

我有一个SQL查询,它在某些条件下选择前5000个数据。现在我的问题是如何从实体框架中编写相同的查询?可能吗?我想知道从实体框架获得此查询的最有效方法。

查询:

select TOP 5000 * from MyData where Type=1 and UPC not in (
select UPC from MyData where Type=2 AND UPC IS NOT NULL)

C#实体:

using (var ctx = new db_ProductionEntities())
{
    //var items = ctx.MyData.Take(10).ToList(); need to know how to write query here
}

1 个答案:

答案 0 :(得分:0)

var answer = (from d1 in ctx.MyData 
              where d1.Type == 1 and 
                    !(from d2 in ctx.MyData 
                      where d2.Type == 2 and d2.UPC != null
                      select d2.UPC 
                     ).Contains(d1.UPC)
              order by d1.Id //or some other field, it's needed for "Take"
              select d1).Take(5000).ToList();