ADO.NET 实体框架和标识列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/120755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ADO.NET Entity Framework and identity columns
提问by biozinc
Is the Entity Framework aware of identity columns?
实体框架是否知道标识列?
I am using SQL Server 2005 Express Edition and have several tables where the primary key is an identity column. when I use these tables to create an entity model and use the model in conjunction with an entity datasource bond to a formview in order to create a new entity I am asked to enter a value for the identity column. Is there a way to make the framework not ask for values for identity columns?
我正在使用 SQL Server 2005 Express Edition 并且有几个表,其中主键是一个标识列。当我使用这些表创建实体模型并将该模型与实体数据源绑定到表单视图以创建新实体时,我被要求为标识列输入一个值。有没有办法让框架不要求标识列的值?
回答by biozinc
I know this post is quite old, but this may help the next person arriving hear via a Google search for "Entitiy Framework" and "Identity".
我知道这篇文章已经很旧了,但这可能会帮助下一个人通过谷歌搜索“实体框架”和“身份”来听到。
It seems that Entity Frameworks does respect server-generated primary keys, as the case would be if the "Identity" property is set. However, the application side model still requires a primary key to be supplied in the CreateYourEntityHeremethod. The key specified here is discarded upon the SaveChanges()call to the context.
实体框架似乎确实尊重服务器生成的主键,就像设置“身份”属性一样。但是,应用程序端模型仍然需要在CreateYourEntityHere方法中提供主键。此处指定的键在SaveChanges()调用上下文时被丢弃。
The page heregives the detailed information regarding this.
此处的页面提供了有关此的详细信息。
回答by Siva
If you are using Entity Framework 5, you can use the following attribute.
如果您使用的是实体框架 5,则可以使用以下属性。
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
回答by YeahStu
You should set the identity columns' identity specification so that the (Is Identity) property is set to true. You can do this in your table designer in SSMS. Then you may need to update the entity data model.
您应该设置标识列的标识规范,以便 (Is Identity) 属性设置为 true。您可以在 SSMS 的表设计器中执行此操作。然后您可能需要更新实体数据模型。
Perhaps that what you mean by saying the "Primary key is an identity column," or perhaps you missed this step.
也许这就是您所说的“主键是一个标识列”的意思,或者您可能错过了这一步。
回答by John West
This is the best answer I've seen. You have to manually edit the storage layer xml to set StoreGeneratedPattern="Identity"on each primary key of type UniqueIdentifierthat has the default value set to NewID().
这是我见过的最好的答案。您必须手动编辑存储层 xml 以在默认值设置为StoreGeneratedPattern="Identity"的类型的每个主键上进行UniqueIdentifier设置NewID()。
回答by scotta
If all else fails before you rip out your hair - try deleting your EntityModel and re-importing from SQL Server. If you've been tweaking the keys and relationships and relying on the 'update model from database' function it's still a bit buggy in the RC version I've found - a fresh import may help.
如果在你扯掉头发之前所有其他方法都失败了 - 尝试删除你的 EntityModel 并从 SQL Server 重新导入。如果您一直在调整键和关系并依赖“从数据库更新模型”功能,那么在我发现的 RC 版本中仍然存在一些问题 - 新的导入可能会有所帮助。
回答by Biri
Entity Framework is aware and can handle identity columns.
实体框架知道并且可以处理标识列。
Your problem can be maybe not the EF itself but the generated formview of it. Try to delete the input for the identity column from the insert form and let's see what happens.
您的问题可能不是 EF 本身,而是它生成的表单视图。尝试从插入表单中删除标识列的输入,让我们看看会发生什么。
回答by aladd04
In C# you can do something like this to make it aware:
在 C# 中,您可以执行以下操作以使其意识到:
In your FooConfiguration.cs : EntityTypeConfiguration<Foo>:
在您的FooConfiguration.cs : EntityTypeConfiguration<Foo>:
this.Property(x => x.foo).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Then to use it, just be sure to insert the item into the context and call context.SaveChanges()before using x.footo get the updated auto-incremented value. Otherwise x.foowill just be 0 or null.
然后使用它,只需确保将项目插入上下文并context.SaveChanges()在使用之前调用x.foo以获取更新的自动递增值。否则x.foo将只是 0 或 null。
回答by aladd04
Entity framework does not fully understand Identities for some reason. The correct workaround is to set the Setter for that column to Private. This will make any generated UI understand that it should not set the identity value since it is impossible for it to set a private field.
由于某种原因,实体框架不能完全理解身份。正确的解决方法是将该列的 Setter 设置为 Private。这将使任何生成的 UI 明白它不应该设置标识值,因为它不可能设置私有字段。
回答by Nick
What worked for me was setting the StoreGeneratedPattern to None, when it was an Identity column. Now it all works consistently. The main problem with this is editing the models is an extreme chore if you have many models.
对我有用的是将 StoreGeneratedPattern 设置为 None,当它是 Identity 列时。现在,它始终如一地工作。这样做的主要问题是,如果您有很多模型,那么编辑模型是一件极其繁琐的事情。
回答by Fun Chiat Chan
I cannot believe it. Intellisensing ItemCollection yield the single item with ID = 0 after SaveChanges.
我不相信。智能感知 ItemCollection 在 SaveChanges 后产生 ID = 0 的单个项目。
Dim ItemCollection = From d In action.Parameter
Select New STOCK_TYPE With {
.Code = d.ParamValue.<Code>.Value,
.GeneralUseID = d.ParamValue.<GeneralUse>.Value,
}
GtexCtx.STOCK_TYPE.AddObject( ItemCollection.FirstOrDefault)
GtexCtx.SaveChanges()
No matter what I do. After 8 hours including deleting my model, 35 times building and rebuilding, experimenting and editing the XML of EDMX and now almost coming to deleting my whole SQL Server database. At the 36th compile, this dumbfounding solution worked
不管我做什么。8 小时后,包括删除我的模型,35 次构建和重建,试验和编辑 EDMX 的 XML,现在几乎要删除我的整个 SQL Server 数据库。在第 36 次编译时,这个令人哭笑不得的解决方案奏效了
Dim abc = ItemCollection.FirstOrDefault
GtexCtx.STOCK_TYPE.AddObject(abc)
GtexCtx.SaveChanges()
abc.ID yield 41 (the identity i needed)
abc.ID yield 41(我需要的身份)
EDIT: Here's a simple code for thought for looping AddObject and still get ID
编辑:这是一个简单的代码,用于循环 AddObject 并仍然获得 ID
Dim listOfST As List(Of STOCK_TYPE) = ItemCollection.ToList()
For Each q As STOCK_TYPE In listOfST
GtexCtx.STOCK_TYPE.AddObject(q)
Next
GtexCtx.SaveChanges()
...more code for inter-relationship tables
Try Intellisence listOfST after SaveChanges and you will find updated ID. Maybe there's better way but the concept is there
在 SaveChanges 之后尝试 Intellisence listOfST,您会发现更新的 ID。也许有更好的方法,但概念就在那里

