entity-framework - ef core - 多对多关系
问题描述
我最近一直在尝试使用 ef core,但是在 ef core 中的多对多关系中有些东西令人困惑。
public class Location
{
public Guid Id { get; set; }
public ICollection<LocationInstructor> LocationInstructors { get; set; } = new List<LocationInstructor>();
}
public class Instructor
{
public Guid Id { get; set; }
public ICollection<LocationInstructor> LocationInstructors { get; set; } = new List<LocationInstructor>();
}
public class LocationInstructor
{
public Guid LocationId { get; set; }
public Location Location { get; set; }
public Guid InstructorId { get; set; }
public Instructor Instructor { get; set; }
}
并在 dbcontext
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<LocationInstructor>()
.HasKey(bc => new { bc.LocationId, bc.InstructorId });
modelBuilder.Entity<LocationInstructor>()
.HasOne(bc => bc.Location)
.WithMany(b => b.LocationInstructors)
.HasForeignKey(bc => bc.InstructorId);
modelBuilder.Entity<LocationInstructor>()
.HasOne(bc => bc.Instructor)
.WithMany(c => c.LocationInstructors)
.HasForeignKey(bc => bc.LocationId);
}
这是我尝试执行的操作
var instructors = new List<Instructor>
{
new Instructor(),new Instructor()
};
await applicationDbContext.Instructors.AddRangeAsync(instructors);
Location location = new Location();
foreach (var instructor in instructors)
{
location.LocationInstructors.Add(new LocationInstructor { Instructor= instructor, Location=location});
}
await applicationDbContext.Locations.AddAsync(location);
await applicationDbContext.SaveChangesAsync();
所以,我的问题是为什么 2 值不同?我在这里错过了什么吗?
解决方案
你搞砸了关系映射,基本上InstructorId
与Location
和相关LocationId
联Instructor
:
modelBuilder.Entity<LocationInstructor>()
.HasOne(bc => bc.Location) // (1)
.WithMany(b => b.LocationInstructors)
.HasForeignKey(bc => bc.InstructorId); // (1)
modelBuilder.Entity<LocationInstructor>()
.HasOne(bc => bc.Instructor) // (2)
.WithMany(c => c.LocationInstructors)
.HasForeignKey(bc => bc.LocationId); // (2)
当然,它们应该是配对的 ( LocationId
, Location
) 和 ( InstructorId
, Instructor
)
modelBuilder.Entity<LocationInstructor>()
.HasOne(bc => bc.Location) // (1)
.WithMany(b => b.LocationInstructors)
.HasForeignKey(bc => bc.LocationId); // (1)
modelBuilder.Entity<LocationInstructor>()
.HasOne(bc => bc.Instructor) // (2)
.WithMany(c => c.LocationInstructors)
.HasForeignKey(bc => bc.InstructorId); // (2)
顺便说一句,这是默认的常规映射,因此可以跳过这些(约定优于配置)。
推荐阅读
- javascript - 使 HTML 'value' 属性成为链接
- django - 如何在 Jinja2 模板 Django 中计算循环“for in”中的所有元素
- javascript - 反应 | 字符集删除键盘上的数字'
- reactjs - 这是反应钩子的正确方法吗?
- sql-server-2012 - 在 SQL Server 中自定义四舍五入
- django - Django中的自定义字段类型不会发生验证
- python - 所以我在 python 上做一个虚拟助手
- html - 需要在星云菜单中添加徽章
- flutter - Dart 断言如果在构造函数中不为空
- r - 我可以在 2 列之间的范围内识别相同的值吗?