实体框架 SaveChanges - 如何忽略 INSERT 上的 ID / Identity 字段
VB .NET 4 WinForms 应用程序。
我有一个绑定到 IEnumerable(Of MyClass) 的 (DevExpress) 网格。 每当添加新行时,ID 默认为零 (0)。在尝试 SaveChanges 时,EntityFramework 没有意识到作为标识字段意味着它应该忽略插入时的任何内容并只插入其他值。我无法指定 null / Nothing,因为它只是将 ID 保持为零。
我可以手动添加和保存 MyClass 的实例,但我试图让它在网格处理添加/初始化/等新条目的地方工作。据我所知,问题不在于网格,而在于实体框架以及生成的 SQL 和实体类。
{"Cannot insert explicit value for identity column in table 'MyClasses' when IDENTITY_INSERT is set to OFF."}
任何帮助我防止我把笔记本电脑扔出窗外的帮助将不胜感激!
VB .NET 4 WinForms application.
I have a (DevExpress) grid bound to an IEnumerable(Of MyClass).
Whenever a new row is added, the ID defaults to zero (0). On trying to SaveChanges, EntityFramework doesn't realise that being an identity field means it should ignore any contents on insert and just insert the other values. I can't specify null / Nothing because it just keeps the ID as zero.
I can add and save instances of MyClass manually, but I'm trying to get it to work where the grid handles adding/initialising/etc new entries. As far as I can tell, the problem is not with the grid but with Entity Framework and the generated SQL and entity classes.
{"Cannot insert explicit value for identity column in table 'MyClasses' when IDENTITY_INSERT is set to OFF."}
Any assistance to prevent me from throwing my laptop out a window would be greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果实体的属性是数据库中的
Identity
(自动递增值),则在实体模型的 StorageModel 中指定。也许此设置对于您的特定领域不正确。您可以通过打开模型的 edmx 文件并查看StorageModels
部分来检查这一点。它应如下所示:StoreGeneratePattern
必须设置为Identity
。如果存在None
或缺少属性(默认为None
),您确实会收到您所描述的错误,因为 EntityFramework 在这种情况下不知道ID
是一个标识,将为生成的 SQL-INSERT 语句中的列发出一个值。(确保您确实检查了 edmx 文件中的
edmx:StorageModels
部分。edmx:ConceptualModels
部分在该属性也是如此,但它的设置对于您的具体问题并不重要(我认为这仅在从模型创建数据库时才重要,但我不确定。))If a property of an Entity is an
Identity
(auto-incrementing value) in the database is specified in the StorageModel of your Entity Model. Perhaps this setting is not correct for your particular field. You can check this by opening the edmx file of your model and looking into theStorageModels
section. It should look like this:StoreGeneratedPattern
must be set toIdentity
. If there isNone
or the attribute is missing (which defaults toNone
) you get indeed the error you described since EntityFramework doesn't know in this case thatID
is an identity and will issue a value for the column in the generated SQL-INSERT statement.(Make sure you are really checking the
edmx:StorageModels
section in the edmx file. Theedmx:ConceptualModels
section has an attributeannotation:StoreGeneratedPattern
in the property as well but its setting doesn't matter for your specific problem. (I think that's only important when a database gets created from a model, but I'm not sure.))