了解实体框架的多对多关系。为什么我尝试向其中添加更多数据后代码崩溃?

时间:2019-02-11 11:11:30

标签: c# asp.net-core many-to-many entity-framework-core

我正在尝试创建一个结合Employee和Tractor表的联接表,以记录每次为雇员分配/未分配卡车的时间。我能够记录一个初始的employeeID和truckId,但是一旦尝试在不同的时间和日期记录第二个employeeID和truckID的代码就会崩溃。因此,Datetime对象始终是唯一的。

这是显示的错误:

  

SqlException:违反主键约束'PK_DriverTractorsAssignmentHistory'。无法在对象'dbo.DriverTractorsAssignmentHistory'中插入重复键。重复键值为(1、2)。   该声明已终止。

使用多对多关系是每次员工分配卡车时都能想到的一种解决方案。请给我个更好的解决方案

 public class Employee
 { 
    public int EmployeeID { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }

    public int? TractorID { get; set; }
    public virtual Tractor Tractor { get; set; }
    public virtual List<DriverTractorAssignmentHistory>DriverTractorAssignmentHistories { get; set; }
 }

public class Tractor
{
    public int TractorID { get; set; }
    public string TruckNumber {get; set;}
    public string Status { get; set; } 
    public virtual Employee Employee { get; set; }
    public virtual List<DriverTractorAssignmentHistory> DriverTractorAssignmentHistories { get; set; }

    public Tractor()
    {
        Status = "Available";
    }
}


public class TrailerOrderDbContext:DbContext
{
    public DbSet<Employee> Employees { get; set; } 
    public DbSet<DriverTractorAssignmentHistory> DriverTractorsAssignmentHistory { get; set; }
    public DbSet<Tractor> Tractors { get; set; }

    public TrailerOrderDbContext(DbContextOptions<TrailerOrderDbContext> options)
        : base(options)
    {
    }  

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<DriverTractorAssignmentHistory>().HasKey(co => new { co.EmployeeId, co.TractorId });

        modelBuilder.Entity<DriverTractorAssignmentHistory>()
        .HasOne(e => e.Driver)
        .WithMany(c => c.DriverTractorAssignmentHistories)
        .HasForeignKey(trac => trac.TractorId);

        modelBuilder.Entity<DriverTractorAssignmentHistory>()
        .HasOne(trac => trac.Tractor)
        .WithMany(c => c.DriverTractorAssignmentHistories)
        .HasForeignKey(e => e.EmployeeId);
 }

 }

1 个答案:

答案 0 :(得分:3)

OnModelCreating(ModelBuilder modelBuilder)中删除此行代码,因为此行代码可防止重复数据输入并防止many-to-many映射:

    modelBuilder.Entity<DriverTractorAssignmentHistory>()
        .HasKey(co => new { co.EmployeeId, co.TractorId });

或在需要unique key的情况下进行以下修改:

    modelBuilder.Entity<DriverTractorAssignmentHistory>()
      .HasKey(co => new { co.EmployeeId, co.TractorId, co.AssignTimestamp };