代码优先实体框架插入具有自定义ID的数据 [英] Code-First Entity Framework inserting data with custom ID
本文介绍了代码优先实体框架插入具有自定义ID的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在项目中使用代码优先EF,当插入具有自定义ID的数据时遇到了问题。
I am using code-first EF in my project and face issue when the data with custom id is being inserted.
当我尝试插入具有自定义ID(例如999)的数据时,EF会忽略它,并将递增的ID插入表中。
When I am trying to insert data with custom ID (for instance 999), EF ignores it and inserts incremented ID into table.
我的模型:
public class Address
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
...
}
如何解决这个问题?
编辑:
1)如何从N开始而不是从0开始递增?
1) How to begin incrementing from N, but not from 0?
2)如果我未指定自定义ID,则DB必须递增并插入自己的ID。如果指定自定义ID,则DB必须插入它。
2) If I don't specify custom ID, DB must increment and inserts own. If I specify custom ID, DB must insert it. Is it possible?
推荐答案
您可以使用以下属性
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
类的密钥或使用fluentAPI
on the key to your class or using fluentAPI
modelBuilder.Entity<Address>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
这篇关于代码优先实体框架插入具有自定义ID的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文