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

梦想与她 提交于 2019-12-02 15:14:39

问题


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, created EntsContext..

    public class EntsContext : DbContext
    {
        public DbSet<Project> Projects { get; set; }
        public DbSet<Phase> Phases { get; set; }
        public DbSet<Iteration> Iterations { get; set; }
        public DbSet<Task> Tasks { get; set; }
        public DbSet<Member> Members { get; set; }
    }

Next step was creating a ProjectController (ASP.NET MVC3) with simple action:

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

The problem is: I am not getting a ProjectManager in view (List/Create scaffolding used). I would like to know if I am doing this wrong or scaffolding generation just ignores my properties, that aren't basic types.
Hmm... It is probably quite obvious.. because generator doesn't know what property of that Type should be used, right?

Well then I could modify my question a bit: What's a solid way to create a Project entity in this scenario (I want to choose a project manager during project creation)? Should I make a ViewModel for this?


回答1:


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.



回答2:


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;}
}


来源:https://stackoverflow.com/questions/5466384/how-to-work-with-navigation-properties-foreign-keys-in-asp-net-mvc-3-and-ef-4

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