LINQ-有条件加入

时间:2019-07-04 16:58:25

标签: entity-framework linq asp.net-core

我有一个条件,其中联接表有条件。假设我有一个名为Mapper Student Teacher的表,其中Mapper表有一个名为AcNoId的列,其中包含两个表Student的ID和Teacher。表结构为

映射器 Mapper

学生 Student

老师 Teacher

TestOption是一个枚举,并定义为

public enum TestOption
{
    Teacher = 1,
    Student = 2
}

现在我有一个条件,如果TestOption是学生类型,则应该执行与Student表的联接,如果是Teacher类型,则应该执行与Teacher表的联接 到目前为止,这就是我尝试过的方式

(from m in _context.Mapper
                   where m.TestOption == TestOption.Student
                       join s in _context.Student
                       on m.AcNoId equals s.Id into tempStudent
                       from st in tempStudent.DefaultIfEmpty()

                   where m.TestOption == TestOption.Teacher
                       join t in _context.Teacher
                       on m.AcNoId equals t.Id into tempTeacher
                       from ta in tempTeacher.DefaultIfEmpty()

                   select new
                   {
                        Type = m.TestOption.ToString(),
                        Student = st.StudentName ?? string.Empty,
                        Teacher = ta.TeacherName ?? string.Empty
                   }).ToList();

此查询代替条件连接,在SQL Profiler上执行以下查询

    exec sp_executesql N'SELECT [m].[TestOption], COALESCE([s].[StudentName], @__Empty_0) AS [Student], COALESCE([t].[TeacherName], @__Empty_1) AS [Teacher]
FROM [Mapper] AS [m]
LEFT JOIN [Student] AS [s] ON [m].[AcNoId] = [s].[Id]
LEFT JOIN [Teacher] AS [t] ON [m].[AcNoId] = [t].[Id]
WHERE ([m].[TestOption] = 2) AND ([m].[TestOption] = 1)',N'@__Empty_0 nvarchar(4000),@__Empty_1 nvarchar(4000)',@__Empty_0=N'',@__Empty_1=N''

我该怎么做??

1 个答案:

答案 0 :(得分:2)

您可以使用以下代码,而无需在join上使用where_context.Mapper语句:

(from m in _context.Mapper
    select new
    {
        Type = m.TestOption.ToString(),
        Student = _context.Student
            .FirstOrDefault(s => 
                m.TestOption == TestOption.Student && 
                s.Id == m.AcNoId) ?? string.Empty,
        Teacher = _context.Teacher
            .FirstOrDefault(t => 
                m.TestOption == TestOption.Teacher && 
                t.Id == m.AcNoId) ?? string.Empty,
    })
    .ToList();