我正在使用以下SQL查询:
SELECT a.AppointmentId,a.Status,a.Type,a.Title,b.Days,d.Description,e.FormId FROM Appointment a (nolock) LEFT JOIN AppointmentFormula b (nolock) ON a.AppointmentId = b.AppointmentId and b.RowStatus = 1 JOIN Type d (nolock) ON a.Type = d.TypeId LEFT JOIN AppointmentForm e (nolock) ON e.AppointmentId = a.AppointmentId WHERE a.RowStatus = 1 AND a.Type = 1 ORDER BY a.Type
我不确定如何在LINQ中实现JOIN.我的所有表都有外键关系.
解决方法
当我离开袖口时你可能不得不稍微调整一下,但还有几个要记住的重要事项.如果在dbml中正确设置了关系,则应该可以隐式执行内部联接,只需通过初始表访问数据.此外,LINQ中的左连接并不像我们希望的那样直截了当,您必须通过DefaultIfEmpty语法才能实现它.我在这里创建了一个匿名类型,但您可能想要放入DTO类或其他类似的东西.在nulls的情况下我也不知道你想做什么,但你可以使用??语法定义一个值,如果值为null,则给出变量.如果您有其他问题,请告诉我……
var query = (from a in context.Appointment join b in context.AppointmentFormula on a.AppointmentId equals b.AppointmentId into temp from c in temp.DefaultIfEmpty() join d in context.AppointmentForm on a.AppointmentID equals e.AppointmentID into temp2 from e in temp2.DefaultIfEmpty() where a.RowStatus == 1 && c.RowStatus == 1 && a.Type == 1 select new {a.AppointmentId,c.Days ?? 0,a.Type.Description,e.FormID ?? 0}).OrderBy(a.Type);