Damb
Damb

Reputation: 14610

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

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?

Upvotes: 1

Views: 3437

Answers (2)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364409

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.

Upvotes: 3

taylonr
taylonr

Reputation: 10790

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

Upvotes: 0

Related Questions