EF 核心正在尝试为 M-to-M 表更新 Role 而不是 ContactRole

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

当 ef core 尝试更新 M-to-M 关系时,我收到

Primary Key violation
错误。这是代码:

// Find the Contact
Contact? Contact = await repository.GetEntityAsync(ContactDto?.Id ?? -1, cancellationToken);

// Check for null
if (Contact == null)
{
   return new OperationResultDto()
   {
      Success = false,
      Error = "Contact not found"
   };
}

mapper.Map(ContactDto, Contact);
Contact resultingContact = await repository.UpdateEntityAsync(Contact, cancellationToken); // << ERROR HERE

这里是模型:

public class ContactDto
{
    public int Id { get; set; }
    public IEnumerable<Role>? Roles { get; set; }
}

public class Contact 
{
    public int Id { get; set; }
    public virtual ICollection<Role>? Roles { get; set; }
}

public class Role 
{
    public Role() => Contacts = new HashSet<Contact>();
    
    public ContactType Type { get; set; }
    public virtual ICollection<Contact> Contacts { get; set; }
}

流畅的API:

/* Role Table */
modelBuilder.Entity<Role>(entity =>
{
    entity.HasKey(e => e.Type);

    entity.HasMany(e => e.Contacts)
          .WithMany(e => e.Roles);

});

/* Contanct Table */
modelBuilder.Entity<Contact>(entity =>
{
    entity.Property(e => e.TradingName).HasMaxLength(100);
    entity.Property(e => e.ParentId);

    entity.HasMany(e => e.Roles)
          .WithMany(e => e.Contacts);
});

当我在调试中查看 SQL 时,它是这样的:

  UPDATE [Contacts] SET [BreedEnumValue] = @p14, [CategoryEnumValue] = @p15, [Destination] = @p16, [ERPStatus] = @p17, [EuComply] = @p18, [Freight] = @p19, [Halal] = @p20, [MSA] = @p21, [NonHGP] = @p22, [ParentId] = @p23, [QualityCode] = @p24, [SaudiComply] = @p25, [Specie] = @p26, [TradingName] = @p27, [TransportBy] = @p28, [TransportMode] = @p29
  WHERE [Id] = @p30;
  SELECT @@ROWCOUNT;

  INSERT INTO [Role] ([Type])
  VALUES (@p31),
  (@p32);

它正在尝试更新角色表,但角色表已经填充。为什么会这样?它应该找不到 TYPE ID 吗?

c# entity-framework ef-fluent-api
© www.soinside.com 2019 - 2024. All rights reserved.