在另一个linq查询中使用结果linq查询

时间:2015-05-26 14:47:32

标签: c# linq

美好的一天!

告诉我是否可以在另一个Linq查询中使用Linq查询的结果? 例如:

    List<Member> memberList = db.Members.Where(m=>m.Year == 20013).ToList();
var result = (from members in memberList
             from documents in Archive.Where(d=>d.MemberId = members.Id).DefaultIfEmpty()
             select new ArchiveRecord
             {
                member = members,
                documentId = documentsId
             }).ToList();

同时第二个请求的执行随着错误而出现(已经有一个与此命令关联的打开的DataReader必须先关闭)。

请告诉我哪里出错了。

谢谢!

3 个答案:

答案 0 :(得分:0)

我不知道如何制作嵌套的linq查询,但我有解决方案。 试试这个:

{{1}}

答案 1 :(得分:0)

在连接字符串中启用多个活动结果集(&#34; MultipleActiveResultSets = True&#34;): https://msdn.microsoft.com/en-us/library/h32h3abf(v=vs.110).aspx

答案 2 :(得分:0)

我相信这应该有用(单一查询):

var memberList = db.Members.Where(m=>m.Year == 20013);
var result = (from members in memberList
         from documents in Archive.Where(d=>d.MemberId = members.Id).DefaultIfEmpty()
         select new ArchiveRecord
         {
            member = members,
            documentId = documentsId
         }).ToList();

这绝对应该有效(单一查询):

var result = (from members in db.Members
         from documents in Archive.Where(d=>d.MemberId = members.Id).DefaultIfEmpty()
         where members.year == 20013
         select new ArchiveRecord
         {
            member = members,
            documentId = documentsId
         }).ToList();

和这(两个查询):

var membersIds = db.Members
  .Where(m => m.Year == 20013)
  .Select(m => m.Id)
  .ToList();

var result = (from documents in Archive.Where(d => membersIds.Contains(d.MemberId)).DefultIfEmpty()
             select new ArchiveRecord
             {
                 member = members,
                 documentId = documentsId
              }).ToList();

并假设您已在要归档的成员上创建了导航属性,并且它是1-many关系(单个查询):

var result=db.Archives
  .Where(a=>a.Member.Year==20013)
  .Select(a=> new ArchiveRecord {
    member=a.Member,
    documentId=a.documentsId
  }).ToList();