【问题标题】:DbSet<T>.AddAsync is setting an id value on an identity column causing an exceptionDbSet<T>.AddAsync 在导致异常的标识列上设置 id 值
【发布时间】:2021-02-26 16:58:37
【问题描述】:

我有一个班级订单,它与其他 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&lt;TEntity&gt;().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() 方法的问题。

【问题讨论】:

  • 问题是什么?
  • 我怎样才能使它与 UsedIdentityColumn 一起工作
  • 好问题! ValueGeneratedOnAdd() 有什么问题,因为它对你有用? UsedIdentityColumn 在以前版本的 EF 中使用过。
  • 我希望加载属于该对象的额外属性,而不是两次访问数据库,我可以使用 var memberEntry = _context.Entry(newEntityToRet).Member(navProp); if (memberEntry is DbCollectionEntry collectionMember) collectionMember.Load();整件事把我逼到了这一步,我想也许使用 UseIdColumn 我不会对这个 Member 方法有任何问题,但最后又是一个大问题,为什么它不起作用
  • 我仍然看不到任何区别,但尝试删除此 builder.Property(dt => dt.Id).UseIdentityColumn();一点也不。默认情况下。

标签: c# entity-framework-core ef-code-first ef-code-first-mapping


【解决方案1】:

首先,PK流畅配置

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&lt;int&gt;))。

【讨论】:

    猜你喜欢
    • 2013-09-12
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    相关资源
    最近更新 更多