在EF MVC中应用左内联接

时间:2019-09-20 03:05:27

标签: asp.net-mvc entity-framework


我有以下SQL语法:

select      a.year, a.Month, 
            a.DocumentNumber, b.BoxNumber, 
            c.LocationShortName, d.RackShortName
from        MasterAP a 
            left join RecordManagementAP b on a.MasterAPID = b.MasterAPID
            left join MasterLocation c on b.LocationID = c.LocationID
            left join MasterRack d on b.RackID = d.RackID
where       a.Month = '2'

如何在MVC中将该语法应用于EF语法?我目前在EF中的语法是:

var recordManagementAPs = db.RecordManagementAPs.Include(r => r.MasterAP).Include(r => r.MasterLocation).Include(r => r.MasterRack);
return View(recordManagementAPs.ToList());

有什么主意吗?
非常感谢。
谢谢。

2 个答案:

答案 0 :(得分:1)

投影。

为视图数据声明视图模型。 (而不是传递实体。)

[Serializable]
public class RecordDetailViewModel
{
    public int MasterAPId { get; set; }
    public string Year { get; set; }
    public string Month { get; set; }
    public string DocumentNumber { get; set; }
    public string BoxNumber { get; set; }
    public string LocationShortName { get; set; }
    public string RackShortName { get; set; }
}

将您的实体查询投影到视图模型中并返回:

var viewModels = db.MasterAPs
    .Where(x => x.Month == month) // "2"
    .Select(x => new RecordDetailViewModel
    {
        MasterAPId = x.MasterAPId,
        Year = x.Year,
        Month = x.Month,
        DocumentNumber = x.DocumentNumber,
        BoxNumber = x.RecordManagementAP.BoxNumber,
        LocationShortName = x.MasterLocation.LocationShortName,
        RackShortName = x.MasterRack.RackShortName
     }).ToList();

假设您的实体关系已映射。

当您返回整个实体并希望预取相关实体(包括它们)时,使用Include关键字,而不是在访问它们时延迟加载它们。通常,仅当您想要执行更新之类的操作时,才应检索实体(及相关实体),在该更新中,您可以接受视图模型或一组字段以从视图中进行更新,加载实体并应用更新,然后再保存实体。不要将实体传递给视图。这会暴露出比您所需要的更多有关您的域的信息,需要更多的内存,并且在序列化关系时可能导致错误或性能陷阱。从视图接收实体会更糟,因为它会使您的系统容易受到意外篡改,潜在的附加参考错误以及陈旧更改覆盖数据的攻击。<​​/ p>

答案 1 :(得分:0)

您可以通过以下方式编写查询:

var query = (from a in Context.MasterAP
            join b in Context.RecordManagementAP on new { a.MasterAPID } equals new { b.MasterAPID }
            into b1
            from b in b1.DefaultIfEmpty()
            join c in Context.MasterLocation on new { b.LocationID } equals new { c.LocationID }
            into c1
            from c in c1.DefaultIfEmpty()
            join d in Context.MasterRack on new { b.RackID } equals new { d.RackID }
            into d1
            from d in d1.DefaultIfEmpty()
            where a.Month == 2
            select new //Write YourModelName Here After new kwyword
            {
                Year = a.Year,
                Month = a.Month,
                DocumentNumber = a.DocumentNumber,
                BoxNumber = b.BoxNumber,
                LocationShortName = c.LocationShortName, 
                RackShortName = d.RackShortName
            });