.net core EF Fluent API配置外键
电脑版发表于:2021/12/21 17:14
和以前的写法变了一点点,以前HasRequired换成HasOne即可。
以前的写法:
//1:先配置多的一方(按照多对一方式来配置) modelBuilder.Entity().HasRequired(a => a.userinfo).WithMany(a => a.pets).HasForeignKey(a => a.UserId); //2:先配置一的一方(按照一对多方式来配置,相当于就是换个顺序) modelBuilder.Entity().HasMany(a => a.pets).WithRequired(a => a.userinfo).HasForeignKey(a => a.UserId);
现在的写法:
protected override void OnModelCreating(ModelBuilder modelBuilder) { //配置外键 //方法1: modelBuilder.Entity<Student>().HasOne(a => a.UserParent).WithMany(a => a.Students).HasForeignKey(a => a.MyUserParentId); //方法2: modelBuilder.Entity<UserParent>().HasMany(a => a.Students).WithOne(a => a.UserParent).HasForeignKey(a => a.MyUserParentId); }