如何让一个实体的主键成为 EF4 代码优先中的另一个实体?

发布于 2024-10-18 04:00:40 字数 662 浏览 2 评论 0原文

假设我有一个 Post 实体,并且我想存储对 post 对象的所有更改,因此我还有一个 PostHistory 实体。现在,我将历史定义如下:

public class PostHistory
{
   public virtual Post Post { get; set; }

   //... properties of the posthistory object
}

问题是我不知道如何让它与 EF4 Code-First 一起使用。起初模型构建失败,因为没有为 PostHistory 定义主键。因此,在我的上下文中,我调用

modelBuilder.Entity<PostHistory>().HasKey(x => x.Post);

并发生以下异常:

System.MissingMethodException: No parameterless constructor defined for this object..

该异常不是在谈论 PostHistory 对象没有无参数构造函数,因为我添加了一个,但它没有帮助。

有什么想法如何实现这一点?

Say I have a Post entity, and I want to store all changes to post objects, so I also have a PostHistory entity. Right now I would define the history as something like this:

public class PostHistory
{
   public virtual Post Post { get; set; }

   //... properties of the posthistory object
}

The problem is I can't figure out how to get this to work with EF4 Code-First. At first model building fails because there is no primary key defined for PostHistory. So in my Context I call

modelBuilder.Entity<PostHistory>().HasKey(x => x.Post);

And the following exception occurs:

System.MissingMethodException: No parameterless constructor defined for this object..

That exception is not talking about the PostHistory object not having a parameterless constructor, because I added one and it didn't help.

Any ideas how to accomplish this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

混吃等死 2024-10-25 04:00:40
public class Post {
    [Key, DatabaseGenerated(DatabaseGenerationOption.Identity)]
    public int Id { get; set; }

    public virtual ICollection<PostHistory> Histories { get; set; }
}

public class PostHistory {
    [Key, DatabaseGenerated(DatabaseGenerationOption.Identity)]
    public int Id { get; set; }

    public int PostId { get; set; }
    public virtual Post Post { get; set; }

   //... properties of the posthistory object
}
public class Post {
    [Key, DatabaseGenerated(DatabaseGenerationOption.Identity)]
    public int Id { get; set; }

    public virtual ICollection<PostHistory> Histories { get; set; }
}

public class PostHistory {
    [Key, DatabaseGenerated(DatabaseGenerationOption.Identity)]
    public int Id { get; set; }

    public int PostId { get; set; }
    public virtual Post Post { get; set; }

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