实体框架核心一对一关系在SQL Server中生成一对多

时间:2016-05-31 04:04:01

标签: entity-framework-core

对于基于本教程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; }
}

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

enter image description here

什么是解决方案?

2 个答案:

答案 0 :(得分:2)

您的代码看起来很好,并且您实际上在BlogBlogImage对象之间创建了1:1的关系,而EF Core通过允许您在这两个对象之间进行双向关联来识别这一点。

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

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

现在,如果您想创建一个 Shared Primary Key Association ,那么@Gert提供的答案是可行的方法,但如果您打算在独特的外国人上创建一对一的关联密钥(即BlogForeignKey)或基本上One-to-One Foreign Key Association然后不更改您的代码,只需在BlogForeignKey列上手动创建一个唯一约束,并等待scheduled的RTM版本由本月底。

答案 1 :(得分:1)

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
相关问题