簡體   English   中英

如何使用 Entity Framework 6 在 ID 列中保存自定義值

[英]How to save custom value in ID column using Entity Framework 6

我正在使用代碼優先方法,我不知道如何將自定義 id 傳遞到 ID 列每當我嘗試傳遞 id 時,它都會顯示以下錯誤:

無法將 null 插入表 Orders.ID 插入失敗

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; }
}

編輯-2

在添加 ID 后,它現在拋出另一個錯誤 Invalid column name 'ID' Invalid column name 'ID'

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

考慮到您的情況,您可以通過以下方式實施。 在您add migration command之前,我已經解決了使用此命令的問題,在此之前您可以像下面這樣添加

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

雖然您可以為非主鍵列添加預期的序列,但到目前為止我已經測試它不適用於主鍵列,因為遷移總是添加此命令。 強制SQL server to take the controls of identity

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

注意:所以我們需要添加上面提到的命令來覆蓋它。 根據需要實現自定義身份。

希望它能幫助您實現目標。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM