目录
EF Core一对一
关系属性
关系配置
使用
EF Core多对多
关系属性
关系配置
使用
EF Core一对一
关系属性
必须显式的在其中一个实体类中声明一个外键属性,可以在Order建立Delivery,也可以在Delivery建立OrderId
class Order
{public long Id { get; set; }public string Name { get; set; }public string Address { get; set; }public Delivery Delivery { get; set; }
}class Delivery
{public long Id { get; set; }public string CompanyName { get; set; }public string Number { get; set; }public Order Order { get; set; }public long OrderId { get; set; }
}
关系配置
class OrderConfig : IEntityTypeConfiguration<Order>{public void Configure(EntityTypeBuilder<Order> builder){builder.ToTable("T_Orders");builder.HasOne(o => o.Delivery).WithOne(p => p.Order).HasForeignKey<Delivery>(p => p.OrderId);}}class DeliveryConfig : IEntityTypeConfiguration<Delivery>
{public void Configure(EntityTypeBuilder<Delivery> builder){builder.ToTable("T_Deliverys");}
}
使用
static async Task Main(string[] args)
{using (MyDbContext ctx = new MyDbContext()){Order o1 = new Order{Name="书",Address="中国"};Delivery d1 = new Delivery{CompanyName="顺丰",Number="SF25646",Order=o1};ctx.Deliverys.Add(d1);await ctx.SaveChangesAsync();}
}
EF Core多对多
EF Core5.0开始,才正式支持多对多
关系属性
class Student
{public int Id { get; set; }public string Name { get; set; }public List<Teacher> Teachers { get; set; } = new List<Teacher>();
}class Teacher
{public int Id { get; set; }public string Name { get; set; }public List<Student> Students { get; set; } = new List<Student>();
}
关系配置
class StudentConfig : IEntityTypeConfiguration<Student>
{public void Configure(EntityTypeBuilder<Student> builder){builder.ToTable("T_Students");builder.HasMany(o => o.Teachers).WithMany(t => t.Students).UsingEntity(j => j.ToTable("T_Student_Teachers"));}
}class TeacherConfig : IEntityTypeConfiguration<Teacher>
{public void Configure(EntityTypeBuilder<Teacher> builder){builder.ToTable("T_teachers");}
}
使用
class Program
{static async Task Main(string[] args){using (MyDbContext ctx = new MyDbContext()){//插入Student s1 = new Student { Name = "张三" };Student s2 = new Student { Name = "李四" };Student s3 = new Student { Name = "王五" };Teacher t1 = new Teacher { Name = "Tom" };Teacher t2 = new Teacher { Name = "Jerry" };Teacher t3 = new Teacher { Name = "Bob" };s1.Teachers.Add(t1);s1.Teachers.Add(t2);s2.Teachers.Add(t2);s2.Teachers.Add(t3);s3.Teachers.Add(t1);s3.Teachers.Add(t2);s3.Teachers.Add(t3);ctx.Students.Add(s1);ctx.Students.Add(s2);ctx.Students.Add(s3);await ctx.SaveChangesAsync();//查询var teachers = ctx.Teachers.Include(t => t.Students);foreach (var t in teachers){Console.WriteLine(t.Name);foreach (var s in t.Students){Console.WriteLine("\t" + s.Name);}}}}
}