EF Core中通过Fluent API配置一对一关系
作者:互联网
继续配置实体之间的第三种关系,即一对一的关系。
以考研报名为例,一个人有唯一的身份证号,在首次报名时会生成一个唯一的考试号,这样身份证号和考试号就是一对一的关系。
同样提供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;
}
标签:Core,set,Exam,get,EF,Fluent,Person,modelBuilder,public 来源: https://www.cnblogs.com/guwei4037/p/16106034.html