EF6.1 Code First:1:1 或添加记录和外键的零问题

EF6.1 Code First: 1:1 or zero issue with adding records and foreign keys

我有两个实体,Executive 和 User。用户可以是执行官,但执行官必须是用户。

行政人员:

public class Executive
{
    [Key]
    public int ExecutiveId { get; set; }

    // every executive is a user
    public int UserId { get; set; }
    [ForeignKey("UserId")]
    public virtual User User { get; set; }...and so on

用户:

 public class User
{
    [Key]
    public int UserId { get; set; }

    public int? ExecutiveId { get; set; }
    [ForeignKey("ExecutiveId")]
    public virtual Executive Executive { get; set; }... and so on (note the nullable ExecutiveId)

CMS 上下文:

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        modelBuilder.Entity<Executive>()
            .HasRequired(x => x.User)
            .WithOptional(s => s.Executive)
            .WillCascadeOnDelete(false); ... and so on

所以,我在初始化程序中添加了两个用户和一个执行者,并且像这样添加了一个执行者:

 var users = new List<User>
        {
            new User{ EmailAddress="a@a.com", LastName="D'Amore", FirstName="Beau", PhoneNumber="888-555-1212"},          
            new User{ EmailAddress="b@b.com", LastName="Munster", FirstName="Herman", PhoneNumber="123-555-7878"}          
        };
        users.ForEach(s => context.Users.Add(s));
        context.SaveChanges();

  Executive exec = new Executive();
        exec.ExecutiveBlurb = "test blurb";
        exec.ExecutiveTitle = "President";
        exec.ProfilePictureContent = new Content { ContentBytes = File.ReadAllBytes("c:\exec.jpg"), AddedDate = DateTime.Now, AddedByUserId = 1 };
        exec.ProfileSidePictureContent = new Content { ContentBytes = File.ReadAllBytes("c:\exec2.jpg"), AddedDate = DateTime.Now, AddedByUserId = 1 };
        exec.UserId = 1;
        exec.User = users.Where(x => x.UserId == 1).First();
        exec.ExecutiveSections = context.ExecutiveSections.Where(x => x.SectionName == "Executive Team" && x.SectionName == "Acquisitions").ToList();
        context.Executives.Add(exec);

事实是,Executive 是在 User 之后创建的(应该是因为它是 1:1 或 0)但是 User 永远不会设置 ExecutiveId...EF 不会自动处理外键?就像,当我将 objectA 添加到 objectB 时,通常,将 A 设置为具有 B,因为它是外键,将 B 设置为具有 A,因为它在往复 属性... 我遗漏了 1:1 或 0 的内容事物。 有什么建议吗?

在 1:0..1 关系或任何其他类型的一对一关系中使用 Entity Framework 时,关系每一侧的两个实体必须共享一个主键。对于依赖的任何一方——对于必需的-可选的,它将是可选的一方——主键 属性 也是外键。

在您的情况下,您有一些 conflicting/redundant 注释和流畅的 API 调用,但流畅的 API 优先,因此 Executive.UserIdUser.ExecutiveId 是被忽略了。您创建的 Executive 应该以 exec.User.UserId == exec.ExecutiveId.

结尾

这是有道理的,因为你永远不会有没有 UserExecutive,并且永远不会有超过一个 Executive 绑定到同一个 User ,因此 Executive 不需要单独的主键。

https://msdn.microsoft.com/en-us/data/jj591620#RequiredToOptional