DbSet<T>.AddAsync 在标识列上设置 id 值导致异常

问题描述

我有一个类订单,它与其他 2 个类有关系,但问题在于这里的 Id

public class Order 
{
    public int Id { get; set; }
    public bool IsDeleted { get; set; }
    public string CreatedBy { get; set; }
    public string UpdatedBy { get; set; }
    public DateTime? CreatedOn { get; set; }
    public DateTime? UpdatedOn { get; set; }
    public string Symbol { get; set; }
    //public string SymbolName { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }
    public int StatusId { get; set; }
    public OrderStatus Status { get; set; }
    public int TradingActionId { get; set; }
    public TradingAction TradingAction { get; set; }
    public string Notes { get; set; }

}

我以这种方式映射:

public class OrderMap : IEntityTypeConfiguration<Order>
{
    public override void Configure(EntityTypeBuilder<Order> builder)
    {
        builder.ToTable("Order");

        builder.HasKey(p => p.Id);
        builder.Property(dt => dt.Id).UseIdentityColumn();

        builder.Property(x => x.CreatedBy).HasMaxLength(50).IsRequired();
        builder.Property(x => x.CreatedOn).IsRequired();
        builder.Property(x => x.UpdatedBy).HasMaxLength(50).IsRequired();
        builder.Property(x => x.UpdatedOn).IsRequired();

        builder.HasQueryFilter(app => !app.IsDeleted);
        builder.Property(je => je.Symbol).HasMaxLength(10).IsRequired();
        //builder.Property(je => je.SymbolName).HasMaxLength(300).IsRequired();
        builder.Property(je => je.Quantity).IsRequired();
        builder.Property(je => je.Price).IsRequired();
        builder.Property(je => je.Notes).HasMaxLength(300);

        builder.HasOne<OrderStatus>(order => order.Status)
            .WithMany(os => os.Orders)
            .HasForeignKey(order => order.Id)
            .OnDelete(DeleteBehavior.Restrict)
            .IsRequired(false); ;

        builder.HasOne<TradingAction>(order => order.TradingAction)
            .WithMany(ta => ta.Orders)
            .HasForeignKey(orders => orders.Id)
            .OnDelete(DeleteBehavior.Restrict)
            .IsRequired(false); ;
    }
}

在我的存储库中,我正在使用这种方法来保存,因为您可以看到属性 TradingActionStatus 不是由我填写的,但它们的 ID 已传递给要创建的订单。

  var entity = new Order
  {
   TradingActionId = 1,StatusId = 2,Notes = source.Notes,Price = source.Price,Symbol = source.Symbol,Quantity = source.Quantity,CreatedOn = dateTimeNow,UpdatedOn = dateTimeNow,UpdatedBy = "test",CreatedBy = "test"
};
_context.Set<TEntity>().AddAsync(entity);

在这种情况下,_context.Set<TEntity>().AddAsync(entity); 抛出一个异常说:

当 IDENTITY_INSERT 时无法为标识列插入显式值 设置为关闭。

运行 SqlProfiler 我得到这个查询:

exec sp_executesql N'SET NOCOUNT ON;
INSERT INTO [Order] ([Id],[CreatedBy],[CreatedOn],[IsDeleted],[Notes],[Price],[Quantity],[StatusId],[Symbol],[TradingActionId],[UpdatedBy],[UpdatedOn])
VALUES (@p0,@p1,@p2,@p3,@p4,@p5,@p6,@p7,@p8,@p9,@p10,@p11);
',N'@p0 int,@p1 nvarchar(50),@p2 datetime2(7),@p3 bit,@p4 nvarchar(300),@p5 decimal(3,1),@p6 int,@p7 int,@p8 nvarchar(10),@p9 int,@p10 nvarchar(50),@p11 datetime2(7)',@p0=-2147482647,@p1=N'test',@p2='2021-02-26 09:10:21.8811175',@p3=0,@p4=N'test',@p5=20.2,@p6=1000,@p7=1,@p8=N'AAL',@p9=2,@p10=N'test',@p11='2021-02-26 09:10:21.8811175'

它告诉我 @p0=-2147482647 什么时候应该自动生成身份。

如果我将此行更改为此行,它将起作用并将属性设置为身份:

builder.Property(dt => dt.Id).ValueGeneratedOnAdd();

这里的问题是不允许我使用 .UseIdentityColumn() 方法。

解决方法

首先,PK fluent配置

builder.HasKey(p => p.Id);
builder.Property(dt => dt.Id).UseIdentityColumn();

是多余的,因为按照惯例两者都是正确的。所以问题应该出在其他地方。

而且确实是在不正确的多对一 FK 映射中(也是冗余的)

builder.HasOne<OrderStatus>(order => order.Status)
    .WithMany(os => os.Orders)
    .HasForeignKey(order => order.Id) // <--
    .OnDelete(DeleteBehavior.Restrict)
    .IsRequired(false);

builder.HasOne<TradingAction>(order => order.TradingAction)
    .WithMany(ta => ta.Orders)
    .HasForeignKey(orders => orders.Id) // <--
    .OnDelete(DeleteBehavior.Restrict)
    .IsRequired(false);

为什么?由于多对一 FK 永远不会自动生成,它们“指向”另一个表中的现有键,因此这些错误配置调用实际上抵消了先前 PK 配置的影响。

要解决这个问题(因为它也会导致不正确的查询),只需将它们删除或分别使用

.HasForeignKey(order => order.StatusId)

.HasForeignKey(orders => orders.TradingActionId)

另请注意,ÌsRequired(false) 对您的 int 等不可空类型 FK 没有影响 - 它们仍将被视为必需的,因为不可空字段不能具有空值。因此也删除它们,如果您真的想要可选的 FK,请将 FK 属性的类型更改为相应的可为空类型(在本例中为 int? (Nullable<int>))。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...