简体   繁体   中英

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

I am using code first approach, I don't know how to pass custom id into ID column Whenever I try to pass id its show the following error:

Can't insert null to table Orders.ID Insert fails

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

After adding on ID its now throwing another error as Invalid column name 'ID' Invalid column name 'ID'

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

Considering your scenario you could implement like below ways. I have work around using this command while you add migration command , before that you could add this like below

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

Though you could add expected sequence for non primary key column but so far I have tested it does't work for primary key column because migration always add this commands. Which enforced SQL server to take the controls of identity

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

Note: So we need to add above mensioned command to override it. Which implement the custom identity as we want.

Hope it will help you to acheive your goal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM