如何在linq中使用SQL查询?

时间:2014-05-26 07:54:24

标签: c# sql sql-server linq

我有一个像这样的SQL查询:

 SELECT [Id],[WfInstanceId]
   FROM [WfTask]
  WHERE DocId IN 
        (SELECT [Id]
           FROM [FormInstance]
          WHERE FormId = '91889C15-7205-4467-B626-3C4AAB22567B')

如何将它与linq一起使用?我想返回一个IQueryable并将其传递给我的网格视图。

2 个答案:

答案 0 :(得分:2)

var q = from row in WfTast
        where (from x in FormInstance
               where FormId='91889C15-7205-4467-B626-3C4AAB22567B' &&
               row.DocId = id
               select x).Any()
        select Id, WfInstanceId;

或者,加入:

var q = from Task in WfTast
        join Form in (FormInstance.Where(x => x.FormId='91889C15-7205-4467-B626-3C4AAB22567B')
        on Task.DocId = Form.Id
        select Task.Id, Task.WfInstanceId;

或者,只有flunet语法:

var q = WfTast.Where(wt => FormInstance.Where(x => x.FormId='91889C15-7205-4467-B626-3C4AAB22567B' &&
                                                   wt.DocId = x.id).Any());

或:

var formsIdCollection =  FormInstance.Where(x => x.FormId='91889C15-7205-4467-B626-3C4AAB22567B').Select(x => x.id); 
// if you reuse this list, add at end this: .ToArray();

var q = from row in WfTast
        where formsIdCollection.Contains(row.DocId)
        select Id, WfInstanceId;

答案 1 :(得分:0)

var query = DatabaseContext.WfTask.Where(
                i => DatabaseContext.FormInstane
                    .Where(fi => fi.FormId = '...')
                    .Select(fi => fi.Id)
                    .Contains(i.DocId));