问题描述
我正在使用EF4和POCO。在我们的模型中,我们有一个带有ID属性的用户类,它是一个Guid,在存储模型和概念模型中,我们使用StoreGeneratedPattern = Identity,在SQL Server中,此列的默认值为NEWID()。这是
工作正常,可以创建和更新数据库为我们生成id的用户。该系统由其他几个系统通过WCF服务使用。
I am using EF4 with POCOs. In our model we have a user class with and ID property which is a Guid and in the storagemodel and conceptual model we are using StoreGeneratedPattern=Identity, in SQL Server this column has a default value of NEWID(). This is working fine with creating and updating users where the id is generated for us by the database. This system is used by several other systems through a WCF service.
现在其中一个要求正在发生变化,其中一个系统希望在创建时使用Guids提供的Guids指定自己的ID用户。
Now one of the requirements are changing and one of the other systems wants to specify their own IDs with Guids provided by them when creating users.
这似乎是不可能的,只要我们在我们的ef模型中有StoreGeneratedPattern = Identity,我就尝试了以下内容:
This seems to be impossible as long as we have StoreGeneratedPattern=Identity in our ef model, i have tried the following:
1)在保存之前将Guid提供的Guid添加到用户ID中,当数据插入数据库时,不使用提供的guid,而是将数据库中创建的Guid作为新ID返回
1) added the Guid provided by the to the user ID before saving, the guid provided is not used when the data gets inserted into the database it is instead returning the Guid created in the database as the new ID
2)尝试将带有自定义ID的用户对象附加到上下文并验证EntityKey是否正确,但是将对象的状态更改为已删除EntityKey
2) tried attaching the user object with the custom ID to the context and verified the EntityKey is correct, but changing the state of the object to added kills the EntityKey
3)只需添加具有上下文自定义ID的用户对象也不起作用,因为它不会生成有效的EntityKey
3) just adding the user object with the custom id to the context doesnt work either as it will not generate a valid EntityKey
是否有某种方法可以强制实体框架使用id保存新用户我提供了什么?我希望我不必删除StoreGeneratedPattern = Identity,因为它将是一次大规模的重构。
Is there some way to force entity framework to save the new user with the id i have provided? I am hoping i dont have to remove the StoreGeneratedPattern=Identity as it will be a massive refactoring.
推荐答案
.net中的Guid类型是一个结构,这意味着它不能接收null,而是空guid('00000000-0000-0000-0000-000000000000'),这意味着如果您的列的默认值为newid(),然后永远不会计算默认值。
The Guid type in .net is a struct, which means it cannot receive null, but rather the empty guid ('00000000-0000-0000-0000-000000000000'), which means that if your column has a default value of newid(), then the default value will never be calculated.
您能解释一下您是如何建模数据库和概念模型的吗?你在插入时使用触发器吗?插入的存储过程?
Can you explain how you modeled your database and conceptual model? are you using triggers on insert? stored procedures for the insert?
这篇关于在ef模型中使用StoreGeneratedPattern = Identity手动创建EntityKeys的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!