实体框架 4.1 中具有不同名称的唯一列和导航属性的流畅映射/数据注释?
首先,有没有办法通过使用数据注释或流畅的 API 来告诉 EF 4.1 列必须是唯一的?
其次,关于导航属性,我有两个类 Document 和 User。在文档类中,我有一个 OwnerId (UserId) 属性和一个 Owner (User) 属性。如何告诉 EF 4.1 OwnerId 实际上是 UserId 并且 Owner 是返回到 User 的导航属性?
文档类:
public abstract class Document: BaseEntity
{
public bool IsActive { get; set; }
public string Description { get; set; }
//The UserId
public Guid OwnerId { get; set; }
//The User
public User Owner { get; set; }
}
First, is there a way to tell EF 4.1 that a column needs to be unique by using either data annotations or the fluent API?
Second, regarding navigation properties, I have have 2 classes Document and User. In the document class I have a property for the OwnerId (UserId) and a property for Owner (User). How do I tell EF 4.1 that the OwnerId is really UserId and Owner is a navigation property back to User?
The Document Class:
public abstract class Document: BaseEntity
{
public bool IsActive { get; set; }
public string Description { get; set; }
//The UserId
public Guid OwnerId { get; set; }
//The User
public User Owner { get; set; }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实体框架根本不支持唯一键,因此第一个问题的答案是否定的。
OwnerId
应自动识别为Owner
的外键,除非您映射到外键名称不同的现有数据库。在这种情况下,您可以使用例如:可能不需要外键数据注释,但您可以使用它来显式地将 FK 属性与导航属性配对。
在流畅的映射中,您可以使用:
Entity framework doesn't support unique keys at all so the answer to your first question is no.
OwnerId
should be recognized as foreign key forOwner
automatically unless you map to existing database where the foreign key is named differently. In such case you can use for example:Foreign key data annotation is probably not needed but you can use it to explicitly pair your FK property with navigation property.
In fluent mapping you can use: