Entity Framework 4.2 一对多,无 DbSet

发布于 2024-12-22 18:39:42 字数 948 浏览 2 评论 0原文

我正在尝试与 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

没︽人懂的悲伤 2024-12-29 18:39:42

一方面,您的导航属性必须标记为虚拟:

public class Project
{
    [ForeignKey("ProjectManagerUserId")]
    public virtual User ProjectManager { get; set; }
    public Guid ProjectManagerUserId { get; set; }
}

为什么?

在运行时,EF 4.2 创建一个子类并覆盖此属性,以便从数据库填充它(使 Include 能够用于急切加载等)。

For one thing, your navigation properties have to be marked as virtual:

public class Project
{
    [ForeignKey("ProjectManagerUserId")]
    public virtual User ProjectManager { get; set; }
    public Guid ProjectManagerUserId { get; set; }
}

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文