【问题标题】:Entity Framework core one to one relationship generate one to many in SQL Server实体框架核心一对一关系在 SQL Server 中生成一对多
【发布时间】:2016-05-31 04:04:00
【问题描述】:

对于基于本教程http://ef.readthedocs.io/en/latest/modeling/relationships.html#one-to-one 的实体框架核心(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; }
}

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

什么是解决方案?

【问题讨论】:

  • 什么是问题

标签: entity-framework-core


【解决方案1】:

您的代码看起来不错,实际上您在 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 列上手动创建唯一约束并等待 RTM 版本 scheduled 在本月底发布。

【讨论】:

    【解决方案2】:

    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
    

    【讨论】:

    • 我之前像这段代码测试过,这段代码在迁移中抛出异常
    • 好吧,如果您想要 1:1 关联,这就是您所需要的。如果您在问题中提到了自己的努力和迁移问题,如果会有所帮助。 throw exception 也不是很丰富。有什么例外?
    • 你的代码没问题,我用这个代码测试,不同的是BlogImage实体中的BlogImageId是BlogId。并发生异常。 System.InvalidOperationException:实体类型“WebApplication18.Data.BlogImage”需要定义一个键。在 Microsoft.EntityFrameworkCore.Internal.ModelValidator.ShowError(String message),反正你的代码没问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 2021-05-14
    • 2019-02-14
    • 2017-10-29
    • 1970-01-01
    • 2020-05-31
    相关资源
    最近更新 更多