[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 by fk to the difference principle entity and depended entity, but when you design entitys indistinguishable by convention out easily (this time may be many reasons), migration you perform error.

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.

So at this point you need to use to solve 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);
    }

Also from the design point of view, in fact, author and author biography because it is one - to - one relationship, so the two can actually mapping the actual entity of a table which they share a primary key, is achieved by fluent api called. table splitting Technology:

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

Guess you like

Origin www.cnblogs.com/it-dennis/p/11654211.html