实体框架 4.1 - 创建主键值
快速信息:
- 使用 EF 4.1 Code First。
- 使用没有属性修饰的 POCO 类。
- 在 EntityTypeConfiguration<> 中使用流畅的配置将 POCO 映射到数据库的类。
- 遵循 DDD 模式,使用通用存储库、聚合根、规范等。
问题:
对于将主键设置为身份的实体,DatabaseGenerateOption.Identity 应该可以正常工作。
然而,在我们当前的模式中,有一种“有趣”的方式来创建主键。调用一个存储过程来创建要使用的“下一个”唯一键(为多个不同的表调用相同的存储过程以确保所有表中的唯一键)。这是来自一个遗留结构,我不会在这篇文章中讨论它,但我需要能够实现它。
我将映射设置为 DatabaseGenelatedOption.None。在插入记录之前处理新 ID 检索的最佳方法是什么?我可以在 DbContext 上处理一个事件吗?
谢谢!
Quick info:
- Using EF 4.1 Code First.
- Using POCO classes with no attribute decoration.
- Using fluent configuration in EntityTypeConfiguration<> classes to map POCO to database.
- Following DDD pattern, using generic repositories, aggregate roots, specification, etc.
Problem:
For entities with the primary key set as identity, DatabaseGeneratedOption.Identity should work fine.
However, in our current schema there is an "interesting" way to create primary keys. A stored procedure is called that create the "next" unique key to use (same sproc is called for several different tables to ensure a unique key across all of them). This was from a legacy structure that I'm not going to get into in this post, but I need to be able to implement it.
I am setting the map to DatabaseGeneratedOption.None. What is the best approach to handling the retrieval of the new id right before inserting a record? Is there an event I can handle on the DbContext?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
DatabaseGenerateOption 的值设置 EF 如何处理属性:
None
- 标准属性。 EF 将在选择期间加载其值,允许应用程序修改该值并保留该值。Identity
- EF 期望在插入记录时由数据库设置此属性。插入记录时,EF 会自动将此值加载回实体。它不一定是数据库中的标识列 - 它也可以是触发器生成的值。应用程序无法为标记为身份计算的属性设置值因此,如果您想在应用程序中自己调用该过程,则必须使用
None
。例如,如果您决定使用插入前触发器来执行该过程,则必须使用Identity
。DatabaseGenerateOption.Identity
表示插入记录时将在数据库中设置该值。DatabaseGenerateOption.Compulated
表示每次更新记录时都会在数据库中设置该值。Values of DatabaseGeneratedOption set how EF deals with a property:
None
- standard property. EF will load its value during select, allow application to modify the value and persist the value.Identity
- EF expects that this property will be set by the database when the record is inserted. EF will auto load this value back to entity when the record is inserted. It doesn't have to be identity column in the database - it can be value generated by trigger as well. Application cannot set value for property marked as identityComputed
- EF expects that this property can change in the database after each modification. It reloads the value after every insert or update. Application cannot set value for property marked as identity.So if you want to call the procedure yourselves in your application you must use
None
. If you for example decide to use before insert trigger to execute the procedure you must useIdentity
.DatabaseGeneratedOption.Identity
means that value will be set in the database when the record is inserted.DatabaseGeneratedOption.Computed
means that value will be set in the database each time the record is updated.