简体   繁体   English

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

[英]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:我正在使用代码优先方法,我不知道如何将自定义 id 传递到 ID 列每当我尝试传递 id 时,它都会显示以下错误:

Can't insert null to table Orders.ID Insert fails无法将 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; }
}

EDIT-2编辑-2

After adding on ID its now throwing another error as Invalid column name 'ID' Invalid column name 'ID'在添加 ID 后,它现在抛出另一个错误 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在您add migration command之前,我已经解决了使用此命令的问题,在此之前您可以像下面这样添加

 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强制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.希望它能帮助您实现目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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