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

后端 未结 2 1567
你的背包
你的背包 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:23

    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;}
    }
    
    0 讨论(0)
  • 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.
    0 讨论(0)
提交回复
热议问题