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

后端 未结 2 1595
你的背包
你的背包 2021-01-25 06:49

I started testing a \"workflow\" with EF code first.
First, I created class diagram. Designed few classes - you can see class diagram here
Then I used EF Code First, cre

2条回答
  •  不要未来只要你来
    2021-01-25 07:30

    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.

提交回复
热议问题