EF core -- -- 多对多关系

问题描述 投票:1回答:1

我最近一直在尝试使用ef core,但是在ef core的many-to-many关系中,有一些东西让人困惑。

    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个数值会有差异?我是不是遗漏了什么?

entity-framework asp.net-core .net-core entity-framework-core
1个回答
1
投票

你把关系映射搞乱了,基本上是把多对多的关系关联起来了。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)

顺便说一下,这是默认的常规映射,所以这些可以跳过(常规高于配置)。

© www.soinside.com 2019 - 2024. All rights reserved.