Entity Framework 核心一对一关系在 SQL 服务器中生成一对多

Entity Framework core one to one relationship generate one to many in SQL Server

根据本教程http://ef.readthedocs.io/en/latest/modeling/relationships.html#one-to-one,对于 Entity Framework 核心(rc1 或 rc2)中的一对一关系,我使用此代码:

public class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<BlogImage> BlogImages { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .HasOne(p => p.BlogImage)
            .WithOne(i => i.Blog)
            .HasForeignKey<BlogImage>(b => b.BlogForeignKey);
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public BlogImage BlogImage { get; set; }
}

public class BlogImage
{
    public int BlogImageId { get; set; }
    public byte[] Image { get; set; }
    public string Caption { get; set; }

    public int BlogForeignKey { get; set; }
    public Blog Blog { get; set; }
}

但是在运行迁移之后,检查数据库,我注意到生成的表有以下关系:

什么是解决方案?

BlogImageId 应该是 BlogImage 的主键 Blog 的外键:

public class BlogImage
{
    public int BlogImageId { get; set; }
    public byte[] Image { get; set; }
    public string Caption { get; set; }
    // Removed BlogForeignKey

    public Blog Blog { get; set; }
}

modelBuilder.Entity<Blog>()
    .HasOne(p => p.BlogImage)
    .WithOne(i => i.Blog)
    .HasForeignKey<BlogImage>(b => b.BlogImageId); // BlogImageId is FK

您的代码看起来不错,实际上您在 BlogBlogImage 对象之间创建了 1:1 关系,EF Core 通过允许您在两者之间建立双向关联来识别这一点这两个对象。

唯一的问题是 EF Core 未能 通过在 BlogForeignKey 列上创建唯一约束将此一对一关联转换为数据库,因此您在你的对象模型中有一对一的关联,它映射到你的数据库中的一对多关系。

这是一个Bug in EF Core 这将在最终版本中修复。

现在如果你想创建一个Shared Primary Key Association then the answer provided by @Gert is the way to go but if your intention was to create your one to one association on a unique foreign key (i.e. BlogForeignKey) or basically a One-to-One Foreign Key Association then don't change your code, just manually create a unique constraint on BlogForeignKey column and wait for the RTM version which is scheduled这个月底出来。