How to work with navigation properties (/foreign keys) in ASP.NET MVC 3 and EF 4.1 code first

别等时光非礼了梦想. 提交于 2019-12-02 03:49:28

ProjectManager will not be loaded by default. You must either use lazy loading or eager loading. Eager loading will load ProjectManager when you query Projects:

public ActionResult Index()
{
    using (var db = new EntsContext())
    {
        return View(db.Projects.Include(p => p.ProjectManager).ToList());
    }
}

Lazy loading will load ProjectManager once the property is accessed in the view. To allow lazy loading you must create all your navigation properties as virtual but in your current scenario it isn't good appraoch because:

  • Lazy loading requires opened context. You close context before view is rendered so you will get exception of disposed context.
  • Lazy loading in your case results in N+1 queries to DB where N is number of projects because each project's manager will be queried separately.

I believe you'll need a ProjectManager class, and your Project entity will need to have a property that points to the ProjectManager class.

Something like:

public class Project
{
   public string Description {get; set;}
   public Member ProjectManager {get; set;}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!