EF Core中通過Fluent API配置一對一關係
阿新 • • 發佈:2022-04-06
繼續配置實體之間的第三種關係,即一對一的關係。
以考研報名為例,一個人有唯一的身份證號,在首次報名時會生成一個唯一的考試號,這樣身份證號和考試號就是一對一的關係。
同樣提供ER圖如下:
Person類:
public class Person
{
public string PersonIdentityNum { get; set; }
public string PersonName { get; set; }
public virtual Exam Exam { get; set; }
}
Exam類:
public class Exam { public string ExamNo { get; set; } public decimal ExamScore1 { get; set; } public decimal ExamScore2 { get; set; } public decimal ExamScore3 { get; set; } public decimal ExamScore4 { get; set; } public string PersonIdentityNum { get; set; } public virtual Person Person { get; set; } }
然後在資料庫上下文中配置一對一的關係:
public class MyDbContext : DbContext { public MyDbContext() { } public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); //指定主鍵 modelBuilder.Entity<Person>().ToTable("Person").HasKey(o => o.PersonIdentityNum); modelBuilder.Entity<Exam>().ToTable("Exam").HasKey(o => o.ExamNo); //一個人對應一個考生 modelBuilder.Entity<Person>() .HasOne(o => o.Exam) .WithOne(o => o.Person).HasForeignKey<Exam>(o => o.PersonIdentityNum); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); optionsBuilder.UseSqlServer("server=xxx.xxx.xxx.xxx;database=資料庫名;uid=資料庫賬號;pwd=資料庫賬號密碼;"); } public DbSet<Person> Person { get; set; } public DbSet<Exam> Exam { get; set; } }
最後就可以直接關聯查詢:
using (var db = new ChipContext())
{
//查詢姓名為張三的考試資訊
Exam exam = db.Person.Include(o => o.Exam).FirstOrDefault(o => o.PersonName.Equals("張三")).Exam;
}