Entity Framework 4.2 一对多,无 DbSet
我正在尝试与 EF 4.2 设置一对多关系,但它不起作用。 一些数据:
table "BugNet_Projects"
ProjectManagerUserId uniqueidentifier not null
table "aspnet_Users"
UserId uniqueidentifier not null
class Project
{
[ForeignKey("ProjectManagerUserId")]
public User ProjectManager { get; set; }
public Guid ProjectManagerUserId { get; set; }
}
class User
{
public Guid UserId { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Project>().Map(p => p.ToTable("BugNet_Projects"));
modelBuilder.Entity<User>().Map(u => u.ToTable("aspnet_Users"));
}
请注意,用户实体/aspnet_Users 表没有对项目的引用。数据库中存在从 ProjectManagerUserId 到 UserId 的 FK。当我从上下文请求项目时(使用 .Include("ProjectManager")),ProjectManager 属性始终为 null。 ProjectManagerUserId 属性已正确填充 GUID。
有谁知道我做错了什么?
I'm trying to setup a one-to-many relationship with EF 4.2, but it just won't work.
Some data:
table "BugNet_Projects"
ProjectManagerUserId uniqueidentifier not null
table "aspnet_Users"
UserId uniqueidentifier not null
class Project
{
[ForeignKey("ProjectManagerUserId")]
public User ProjectManager { get; set; }
public Guid ProjectManagerUserId { get; set; }
}
class User
{
public Guid UserId { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Project>().Map(p => p.ToTable("BugNet_Projects"));
modelBuilder.Entity<User>().Map(u => u.ToTable("aspnet_Users"));
}
Note the User entity/aspnet_Users table does not have a reference to Projects. There is a FK in the database from ProjectManagerUserId to UserId. When I request a Project from the Context (with .Include("ProjectManager")), the ProjectManager property is always null. The ProjectManagerUserId property is correctly filled with a GUID.
Does anyone know what I'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一方面,您的导航属性必须标记为虚拟:
为什么?
在运行时,EF 4.2 创建一个子类并覆盖此属性,以便从数据库填充它(使 Include 能够用于急切加载等)。
For one thing, your navigation properties have to be marked as virtual:
Why?
At runtime, EF 4.2 makes a subclass and overrides this property in order to populate it from the db (making Include work for eager loading, etc).