gpt4 book ai didi

entity-framework - ef core - 多对多关系

转载 作者:行者123 更新时间:2023-12-04 10:06:51 27 4
gpt4 key购买 nike

我最近一直在尝试使用 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();

当我运行这个操作时,我可以看到下面的截图
enter image description here

所以,我的问题是为什么 2 值不同?我在这里错过了什么吗?

最佳答案

你搞砸了关系映射,基本上是关联 InstructorIdLocationLocationIdInstructor :

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)

其中 btw 是默认的常规映射,因此可以跳过这些(约定优于配置)。

关于entity-framework - ef core - 多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61543438/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com