如何在ASP.NET MVC 3和EF 4.1 code导航性能(/外键)第一工作 [英] How to work with navigation properties (/foreign keys) in ASP.NET MVC 3 and EF 4.1 code first

查看:119
本文介绍了如何在ASP.NET MVC 3和EF 4.1 code导航性能(/外键)第一工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先开始测试工作流程与EF code。结果
首先,我创建的类图。设计了几堂课 - 你可以在这里看到的类图结果
然后我用EF code首先,创建EntsContext ..

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

下一步用简单的动作创造ProjectController(ASP.NET MVC3):

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

问题是:我没有考虑获得一个ProjectManager(列表/创建用于脚手架)。我想知道如果我这样做不对或棚架一代根本不理会我的特性,不属于基本类型。结果
嗯......这可能是相当明显..因为发电机不知道应该用什么属性,该属性类型的,对不对?

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?

推荐答案

ProjectManager 将不会被默认加载。您必须使用延迟加载或立即加载。预先加载将加载 ProjectManager 当你查询项目

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

延迟加载将加载 ProjectManager 一旦属性在视图访问。为了让懒加载您必须创建所有的导航属性虚拟,但在当前的情况下这是不好的,因为appraoch:

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:


  • 延迟加载需要打开上下文。鉴于之前关闭背景下呈现所以你会得到处置方面的异常。

  • 在您的情况下延迟加载导致N + 1查询数据库,其中N是项目数,因为每个项目的经理将另行查询。

这篇关于如何在ASP.NET MVC 3和EF 4.1 code导航性能(/外键)第一工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆