简体   繁体   English

实体框架分配ID

[英]Entity Framework assigns ID

I'm working on a program using a SQL Server database. 我正在使用SQL Server数据库开发程序。 Using PUT/POST, I'm adding elements to the database. 使用PUT / POST,我将元素添加到数据库中。 I run some code on the data, and then delete them afterwards. 我对数据运行了一些代码,然后将其删除。 The issue now is, that when I add new data, the data added gets added with an increasingly high id number, rather than starting from 0. 现在的问题是,当我添加新数据时,添加的数据添加的ID号越来越高,而不是从0开始。

I searched around, and found something that I thought would work, which is adding the below line above the Id. 我四处搜寻,发现一些我认为会起作用的方法,即将下面的行添加到ID上方。 This, however, doesn't work, and I'm still getting an increasingly large Id number, when put into the database. 但是,这是行不通的,当放入数据库时​​,我的ID号仍然越来越大。

Is there a workaround for this? 有没有解决方法?

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual int Id { get; set; }

public int ProducedkW { get; set; }
public int ConsumedkW { get; set; }

public string Type { get; set; }
public int DifferencekW { get; set; }

There are two possible ways i can think of: 我可以想到两种可能的方法:

  1. Truncate table instead of deleting the records It may throw exception in case it's referenced as foreign key in some other table. 截断表而不删除记录如果在其他表中将其作为外键引用,则可能会引发异常。
  2. Run SET IDENTITY_INSERT <table name> ON on sql server, basically it then allows you to enter values explicitly in identity column. 在SQL Server上运行SET IDENTITY_INSERT <table name> ON ,基本上,它随后允许您在标识列中显式输入值。 But keep in mind , you will have to set id in your code. 但是请记住,您将必须在代码中设置id。 But keep in mind , you may lost uniqueness of your column, you willhave to ensure it progamatically in your code then. 但是请记住,您可能会失去列的唯一性,那么您将必须在程序中按比例确保它的准确性。

As alluded to in the comments, it sounds as though you do not want an IDENTITY column, but rather a regular INT column. 正如注释中提到的那样,听起来好像您不希望使用IDENTITY列,而希望使用常规的INT列。

By removing the IDENTITY attribute of the column you are then free to control the IDs yourself. 通过删除列的IDENTITY属性,您可以自由地自己控制ID。 Just set the ID field on your Entity and when you call DbContext.SaveChanges it will take care of it. 只需在您的实体上设置ID字段,当您调用DbContext.SaveChanges时,它就会处理好它。

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

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