[entity framework core] Entity Framework Core One to One Relationships

https://www.learnentityframeworkcore.com/configuration/one-to-one-relationship-configuration

By Convention

    public class Author
    {
        public int AuthorId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public AuthorBiography Biography { get; set; }
    }
    public class AuthorBiography
    {
        public int AuthorBiographyId { get; set; }
        public string Biography { get; set; }
        public DateTime DateOfBirth { get; set; }
        public string PlaceOfBirth { get; set; }
        public string Nationality { get; set; }
        public int AuthorId { get; set; }
        public Author Author { get; set; }
    }

ef core 通过 fk 去 区别 principle entity 和 depended entity, 但是当你设计的entitys无法通过convention轻松地区别出来时(此时的原因可能有很多), 你执行的migration会报错.

The child/dependent side could not be determined for the one-to-one relationship that was detected between '<entity1.property2>' and '<entity2.property1>'. To identify the child/dependent side of the relationship, configure the foreign key property.

所以此时你需要使用 fluent api 去解决

by fluent api

    public class Author
    {
        public int AuthorId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public AuthorBiography Biography { get; set; }
    }
    public class AuthorBiography
    {
        public int AuthorBiographyId { get; set; }
        public string Biography { get; set; }
        public DateTime DateOfBirth { get; set; }
        public string PlaceOfBirth { get; set; }
        public string Nationality { get; set; }
        public int AuthorRef { get; set; }
        public Author Author { get; set; }
    }

using fluent api:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Author>()
            .HasOne(a => a.Biography)
            .WithOne(b => b.Author)
            .HasForeignKey<AuthorBiography>(b => b.AuthorRef);
    }

另外从这个设计上来看, 其实 author 和 author biography 由于是 one - to - one 的关系, 因此两个entity其实可以mapping到实际的一张表当中. 他们共享一个主键, 通过 fluent api 来实现一种叫做 table splitting 的技术:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    	modelBuilder.Entity<Author>()
    		.HasOne(a => a.AuthorBiography).WithOne(b => b.Author)
    		.HasForeignKey<AuthorBiography>(e => e.AuthorId);
    	modelBuilder.Entity<Author>().ToTable("Authors");
    	modelBuilder.Entity<AuthorBiography>().ToTable("Authors"); 
    }
posted @ 2019-10-11 14:56  YanyuWu  阅读(536)  评论(0编辑  收藏  举报