实体框架SQL在导航属性上不是最优的

时间:2017-09-04 05:31:47

标签: asp.net-mvc performance entity-framework

我有简单的代码优先模型(从db生成),包含3个实体:

[Table("Note")]
public partial class Note
{
    public Note()
    {
        NoteCompanies = new HashSet<NoteCompany>();
    }

    public long ID { get; set; }

    [Column(TypeName = "text")]
    public string Content { get; set; }

    public DateTime Date { get; set; }

    public virtual ICollection<NoteCompany> NoteCompanies { get; set; }

}

[Table("Company")]
public partial class Company
{
    public long ID { get; set; }

    [StringLength(150)]
    public string Name { get; set; }

}

[Table("NoteCompany")]
public partial class NoteCompany
{
    public long ID { get; set; }

    public long NoteID { get; set; }

    public long CompanyID { get; set; }

    public virtual Company Company { get; set; }

}

当我在ASP MVC View中使用这个模型时:

@model Models.Note

<ul>
@for (var company in Model.NoteCompanies.Select( nc => nc.Company ))
{
   <a href="#">@company.Name</a>
}
</ul>

实体框架为每个公司触发单选查询。我希望实体会使用产生JOIN查询,如:

SELECT {fields} 
FROM 
  NoteCompany NC
  INNER JOIN Company C ON NC.CompanyId = C.Id
WHERE
  NC.NoteId = @Param

是否可以强制EF生成JOIN查询而不是单行SELECT

最诚挚的问候 IT人员

1 个答案:

答案 0 :(得分:0)

写这样的东西会更好:

@{
    var ids = Model.NoteCompanies.Select(nc => nc.CompanyID).ToList();
    for (var company in db.Companies.Where(x => ids.Contains(x.ID)).ToList())
    {
       <a href="#">@company.Name</a>
    }
}

或尝试通过NoteCompanies在控制器处获取Companies对应的eager loading

model.NoteCompanies = db.NoteCompanies.Include(x => x.Company).ToList();
return View(model);