如何首先在 ASP.NET MVC 3 和 EF 4.1 代码中使用导航属性(/外键)
我首先开始使用 EF 代码测试“工作流程”。
首先,我创建了类图。设计了几个类 - 你可以在这里看到类图
然后我使用 EF Code First,创建了 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):
public ActionResult Index()
{
using (var db = new EntsContext())
{
return View(db.Projects.ToList());
}
}
问题是:我没有在视图中看到 ProjectManager(使用了 List/Create 脚手架)。我想知道我是否做错了,或者脚手架生成只是忽略了我的属性,这些属性不是基本类型。
嗯...这可能很明显..因为生成器不知道应该使用该类型的什么属性,对吧?
那么我可以稍微修改一下我的问题:在这种情况下创建项目实体的可靠方法是什么(我想在项目创建期间选择项目经理)?我应该为此创建一个 ViewModel 吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
默认情况下不会加载
ProjectManager
。您必须使用延迟加载或预先加载。当您查询Projects
时,急切加载将加载ProjectManager
:一旦在视图中访问该属性,延迟加载将加载
ProjectManager
。要允许延迟加载,您必须将所有导航属性创建为虚拟
,但在当前情况下,这不是一个好的方法,因为:ProjectManager
will not be loaded by default. You must either use lazy loading or eager loading. Eager loading will loadProjectManager
when you queryProjects
:Lazy loading will load
ProjectManager
once the property is accessed in the view. To allow lazy loading you must create all your navigation properties asvirtual
but in your current scenario it isn't good appraoch because:我相信您将需要一个 ProjectManager 类,并且您的 Project 实体将需要有一个指向 ProjectManager 类的属性。
像这样的东西:
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: