ADO.NET 数据模型中的备用/候选键
我需要一个实体,它有两个单独的候选键,其中一个是主键,它是代理身份键,另一个是代表真正唯一属性的备用键。我需要将它们分别放在我的实体中。请注意,我指的不是复合键或多列键。无论如何,我需要将其放在 ADO.NET 数据模型中的实体之一上。可以这样做吗?如果是,请指导我。
拥有第二个键的原因是我需要另一个实体与该键上的第一个实体具有关联(和外键)关系。
更新:我在以下问题中发现了与我非常相似的情况: http://social.msdn.microsoft .com/Forums/en/adodotnetentityframework/thread/a248632a-d305-4c15-8e57-6742457cca94 EF v1 好像不支持这个功能。有谁知道V4(字面意思是第二个版本)是否有此功能?我发现了以下内容,但似乎没有显示任何线索表明该功能已添加到当前版本中: http://blogs.msdn.com/b/adonet/archive/ 2009/05/11/update-on-the-entity-framework-in-net-4-and-visual-studio-2010.aspx
I need to have an entity that has two separate candidate keys where one of them is the primary key, which is a surrogate identity key, and another one that is an alternate key representing the real unique attribute. I need to have them both separately in my entity. Please note that I am not referring to composite or multi-column keys. Anyhow I need to have this on one of my entities in ADO.NET data model. Is it possible to do that? If yes please guide me.
The reason to have the second key is that I need another entity to have an association (and foreign key) relationship with first entity on the that key.
Update: I found a very similar situation to mine in the following question:
http://social.msdn.microsoft.com/Forums/en/adodotnetentityframework/thread/a248632a-d305-4c15-8e57-6742457cca94
It seems that EF v1 does not support this feature. Does anybody know if V4(literally the second version) has this feature or not? I have found the following but it does not seem to show any clues that this feature has been added to the current version: http://blogs.msdn.com/b/adonet/archive/2009/05/11/update-on-the-entity-framework-in-net-4-and-visual-studio-2010.aspx
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实体框架不支持唯一键。在实体模型中,您的第二个键将与其他键一样是字段。您将无法在该键上创建关系,并且 EF 不会检查该键的值是否唯一。但是,如果您的模型基于具有唯一键的现有数据库,您将在数据库层进行此检查。
EF 团队已暗示支持唯一键,但 自 .NET 4.5 起仍然不可用。
Entity framework doesn't support unique keys. In entity model your second key will be field as any other. You will not be able to create relations on that key and EF will not check that value of the key is unique. But if your model will be based on existing database with unique keys you will have this check on database layer.
Support for unique keys has been hinted at by the EF team but remains unavailable as of .NET 4.5.
如果您使用 Code First 和 Fluent API,那么创建两个单独的 DbContext 可能是一个不错的解决方案。您可以为要在导航属性中使用的每个键编写单独的 EntityTypeConfiguration 类。我们在项目中也遇到了这个问题,我写了一篇博客文章描述了我们的解决方案:
If you are using Code First and the fluent API, creating two seperate DbContexts might be a good solution for you. You can write separate EntityTypeConfiguration classes for each of the keys that you want to use in navigation properties. We ran into this issue on our project as well and I wrote a blog post describing our solution: http://mmilleruva.blogspot.com/2013/10/working-with-legacy-database-schemas.html