简体   繁体   English

首先使用非顺序编号进行编码

[英]Code first, using a non-sequential Id

I have a code first project with a few tables, I am trying to determine that for a certain object the Id with which it will be inserted will not be the sequential Id that sql provides but an Id i will provide. 我有一个带有几个表的代码优先项目,我试图确定对于某个对象,将其插入的ID将不是sql提供的顺序ID,而是我将提供的ID。

Although the code in my repository is creating the object properly and assigns it the wanted Id once it is inserted to my DB in the: 尽管我的存储库中的代码可以正确创建对象,并在将其插入到我的数据库后将所需的ID分配给它:

DbContext.Set<Containers>().Add(entity);

It is inserted as the next sequential Id. 它将作为下一个顺序ID插入。

In my code first the Id column for the base Entity from which all my entities derive is: 在我的代码中,首先,我的所有实体都源自的基本实体的Id列是:

public int Id { get; set; }

I am looking the change to the Id's only in this entity. 我正在寻找此实体中唯一的ID更改。 Any suggestions? 有什么建议么?

this is the default behavior: when you don't alter it explicitly, EF will create an autoincrement column on the ID, if it's type is fitting. 这是默认行为:如果您未明确更改它,则EF将在ID上创建一个自动递增列(如果其类型合适)。

To alter it, use Fluent API: 要更改它,请使用Fluent API:

modelBuilder.Entity<Containers>().Property(x=>x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

or Data annotations: 或数据注释:

[DatabaseGenerated(DatabaseGeneratedOption.None)]

Maybe you'll have to run an migration after this to alter the table to non-autoincrement also. 也许在此之后您必须运行迁移,以将表也更改为非自动增量。 If you don't want to do that, you'll have to use Identity insert, wrapped in a transaction, every time you want this behavior. 如果您不想这样做,则每次需要这种行为时,都必须使用包裹在事务中的身份插入。

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

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