实体框架核心一对一关系在SQL Server中生成一对多 [英] Entity Framework core one to one relationship generate one to many in SQL Server

查看:62
本文介绍了实体框架核心一对一关系在SQL Server中生成一对多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于基于本教程的Entity Framework核心(rc1或rc2)中的一对一关系

什么是解决方案?

解决方案

BlogImageId 应该是 BlogImage 的主键外键到博客:

 公共类BlogImage{public int BlogImageId {get;放;}公共字节[]图片{放;}公共字符串Caption {get;放;}//删除BlogForeignKey公共博客博客{get;放;}}modelBuilder.Entity< Blog>().HasOne(p => p.BlogImage).WithOne(i => i.Blog).HasForeignKey< BlogImage>(b => b.BlogImageId);//BlogImageId为FK 

For one-to-one relationship in Entity Framework core (rc1 or rc2) based on this tutorial http://ef.readthedocs.io/en/latest/modeling/relationships.html#one-to-one, I use this code:

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; }
}

But after running the migration, and checking the database, I noticed that the generated tables have the following relationship:

What is solution?

解决方案

BlogImageId should be BlogImage's primary key and the foreign key to 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

这篇关于实体框架核心一对一关系在SQL Server中生成一对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆