用5表写左连接linq查询

时间:2018-01-16 06:28:17

标签: c# linq

我是Linq查询的新手。我想通过左连接获得列表。是否可以在一个linq查询中获取所有数据。

public class Center {
    public int centerId,
    public int customerId,
    public List<Note> notes
}

public class Note {
    public int noteId,
    public int centerId,
    public Instruction instruction
}

public class Instruction {
    public int instructionId,
    public int noteId,
    public int instructionText
}

我尝试编写linq查询,但我没有获得所需格式的数据。我的问题是

var result = (from center in ctx.Center 
    join note in ctx.Note on center.centerId equals note.centerId into joinednote 

    from notes in joinednote.DefaultIfEmpty() 
    join inst in ctx.Instruction on notes.noteID equals args.noteID into joinedinst 

    from instruction in joinedarg.DefaultIfEmpty() 
    select new { center, notes, instruction }
).AsEnumerable().ToList();

1 个答案:

答案 0 :(得分:2)

糟糕的设计导致错误的代码。你将做很多工作来通过适当的设计来获得微不足道的东西。我强烈建议您添加外键,如果在Entity Framework中正确设置了导航属性。

至于查询本身,以获得所需的对象层次结构,而不是像你那样获得平面集合:

var result = (from center in ctx.Center
              select new Center {
                  centerId = center.centerId,
                  customerId = center.customerId,
                  notes = ctx.Note.Where(n => n.centerId == center.centerId)
                                  .Select(n => new Note {
                                      noteId = n.noteId,
                                      centerId = n.centerId,
                                      instruction = ctx.Instruction.FirstOrDedault(i => i.noteId == n.noteId)
                                  })
              });

另一种选择是使用您编写的查询,然后按center分组所有项目,然后按note分组内部组。