天天看點

.net core 一對一的表 建立

.net core 一對一的表 建立

分别在兩張表内建立導航屬性和關聯ID

//ResumeEntity
	public class ResumeEntity: AuditedAggregateRoot<Guid>
    {
        public string Education
        {
            get; set;
        }

        public string StaffId
        {
            get; set;
        }

        public StaffEntity Staff
        {
            get; set;
        }
    }
    
//StaffEntity
    public class StaffEntity: AuditedAggregateRoot<Guid>
    {
        public string Name
        {
            get; set;
        }

        public string Age
        {
            get; set;
        }

        public string ResumeId
        {
            get; set;
        }

        public ResumeEntity Resume
        {
            get; set;
        }
    }
           

需要把其中的一個表做為主體,加上外鍵

// 在使用HasForeignKey時需要指定哪張表有外鍵
			builder.Entity<ResumeEntity>(b =>
            {
                b.ToTable("Resume")
                .HasOne(x => x.Staff)
                .WithOne(x => x.Resume)
                .HasForeignKey<ResumeEntity>(x => x.StaffId);
            });
           

一對一的關系如果不指定主體或者不指定外鍵的話,在生成Migration 時會發生異常

builder.Entity<ResumeEntity>(b =>
            {
                b.ToTable("Resume")
                .HasOne()
            });