简体   繁体   English

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

[英]How can I have the primary key of one entity be another entity in EF4 code-first?

Say I have a Post entity, and I want to store all changes to post objects, so I also have a PostHistory entity. 假设我有一个Post实体,并且我想存储所有对post对象的更改,所以我也有一个PostHistory实体。 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. 问题是我不知道如何使它与EF4 Code-First一起使用。 At first model building fails because there is no primary key defined for PostHistory . 最初,模型构建失败,因为没有为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. 那个例外不是在谈论PostHistory对象没有无参数的构造函数,因为我添加了一个并且它没有帮助。

Any ideas how to accomplish this? 任何想法如何做到这一点?

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM