【问题标题】:How to save custom value in ID column using Entity Framework 6如何使用 Entity Framework 6 在 ID 列中保存自定义值
【发布时间】:2021-10-23 12:42:43
【问题描述】:

我使用的是代码优先方法,我不知道如何将自定义 id 传递到 ID 列每当我尝试传递 id 时,它都会显示以下错误:

无法向表 Orders.ID 插入 null 插入失败

public class Order 
{       
    [Key]
    public int  ID { get; set; } // I WANT THIS COLUMN SHOULD BE SAVED AS "10001,10002,10003" INSTEAD OF "1,2,3,4"
    public string CustomerID { get; set; }
    public string CustomerName { get; set; }
    public string CustomerEmail { get; set; }

    public virtual List<OrderItem> OrderItems { get; set; }
    
    public virtual List<OrderHistory> OrderHistory { get; set; }
}

public class OrderHistory 
{
   
    public int OrderID { get; set; }
    public int OrderStatus { get; set; }
    public string Note { get; set; }
}

public class OrderItem 
{        
    public int OrderID { get; set; }

    [NotMapped]
    public string ProductName { get; set; }
    public int ProductID { get; set; }
  
    public virtual Product Product { get; set; }

    /// <summary>
    /// Item Price is in Order Item because we can have a scenerio where we might charge less or greater than the Product Price.
    /// </summary>
    public decimal ItemPrice { get; set; }

    public int Quantity { get; set; }
}

EDIT-2

添加 ID 后,它现在抛出另一个错误 列名“ID”无效 列名“ID”无效

 [Key]
 [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
 public int ID { get; set; }
    

【问题讨论】:

  • 看起来您可能在 ID 上设置的数据库中有自动增量:w3schools.com/sql/sql_autoincrement.asp
  • 这里是您问题的答案stackoverflow.com/questions/55269266/…
  • @PawZaw 您好,感谢您的快速回放,但 ID 未设置为自动递增且列标识规范为否
  • 如果您不指定任何内容,EF 将自动将该列映射为标识列。看起来你只需要增加身份规范的种子值。
  • 从迁移看来它是行不通的。我在您添加迁移命令时使用此命令,在此之前您可以添加此命令。 migrationBuilder.Sql("DBCC CHECKIDENT ('Order ', RESEED, 10001)"); 虽然您可以为非主键列添加预期的序列,但到目前为止我已经测试它不适用于primary key column,因为迁移总是添加.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn) 这个命令。希望你明白我的观点。

标签: c# asp.net-core entity-framework-core entity-framework-6 ef-code-first


【解决方案1】:

考虑到您的场景,您可以通过以下方式实现。我在你add migration command 时使用这个命令,在此之前你可以像下面这样添加它

 migrationBuilder.Sql("DBCC CHECKIDENT ('Order ', RESEED, 10001)"); 

虽然您可以为非主键列添加预期的序列,但到目前为止我已经测试它不适用于主键列,因为迁移总是添加此命令。其中强制执行SQL server to take the controls of identity

.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn)

注意: 所以我们需要添加上面提到的命令来覆盖它。实现我们想要的自定义身份。

希望它能帮助您实现目标。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 2017-12-30
    • 2023-03-14
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多