使用唯一标识符SQL列类型与实体框架 [英] Using uniqueidentifier SQL column type with Entity framework

查看:132
本文介绍了使用唯一标识符SQL列类型与实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我们的客户表我的主键和身份我用的唯一标识符设置为NEWSEQUENTIALID默认值列()。通过管理工具,插入新行会为ID罚款值。

For my primary key and identity in our Clients table I use uniqueidentifier column with a default value set to newsequentialid(). Inserting new rows through the management tool creates the values for the ID fine.

通过EF从.NET 4 code插入成果转化为零的GUID(00000-0000 ....)插入。我创建一个新的实体,设置一些值,并执行EF AddToClients (例如)。如果调试,值id属性显示零GUID。我没有明确通过设置id的 Guid.NewGuid()在我的code,因为我要离开它关闭的 NEWSEQUENTIALID( )在SQL Server中。现在的问题是,它不工作。第一次code执行行被插入零GUID。它显然失败,下一次会导致主键冲突异常。

Inserting from .NET 4 code via EF results into zero GUIDs (00000-0000....) being inserted. I create the entity with new, set some values and perform EF AddToClients (for instance). If debugged, value for the id property shows zero GUID. I do not explicitly set the id via the Guid.NewGuid() in my code because I want to leave it off to the newsequentialid() in SQL Server. The problem is, it doesn't work. The first time the code is executed row gets inserted with zero GUID. The next time it obviously fails and results in primary key violation exception.

我如何能得到这个,而不必设置GUID在我的客户端code的工作?

How can I get this to work without having to set the GUID in my client code?

推荐答案

您需要更改 StoreGeneratedPattern 值在EF设计属性。将其设置为身份。这将导致的EF避免设置在插入的值,然后捕获它之后插入完成

You need to change the StoreGeneratedPattern value for the property in the EF designer. Set it to Identity. This will cause EF to avoid setting the value on an insert, then capture it after the insert is complete.

请注意,如果您使用的是EF 4,你可能有麻烦,这只能使用设计(见<一href="http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/6b00ae43-01d2-4939-943e-fc47aeec5c2a">this链接)。您可能需要手动编辑的.edmx并设置 StoreGeneratedPattern 在存储模型本身。

Note that if you're using EF 4, you may have trouble with this using the designer only (see this link). You may have to edit the .edmx manually and set the StoreGeneratedPattern in the storage model itself.

这篇关于使用唯一标识符SQL列类型与实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆