Mapping 实体框架4.1中具有不同名称的唯一列和导航属性的流畅映射/数据注释?
首先,有没有一种方法可以告诉EF4.1,通过使用数据注释或fluent API,列需要是唯一的 第二,关于导航属性,我有两个类:文档和用户。在document类中,我有一个OwnerId(UserId)属性和一个Owner(User)属性。我如何告诉EF4.1 OwnerId实际上是UserId,而Owner是返回给用户的导航属性 文档类:Mapping 实体框架4.1中具有不同名称的唯一列和导航属性的流畅映射/数据注释?,mapping,data-annotations,entity-framework-4.1,fluent-interface,Mapping,Data Annotations,Entity Framework 4.1,Fluent Interface,首先,有没有一种方法可以告诉EF4.1,通过使用数据注释或fluent API,列需要是唯一的 第二,关于导航属性,我有两个类:文档和用户。在document类中,我有一个OwnerId(UserId)属性和一个Owner(User)属性。我如何告诉EF4.1 OwnerId实际上是UserId,而Owner是返回给用户的导航属性 文档类: public abstract class Document: BaseEntity { public bool IsActive
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; }
}
实体框架根本不支持唯一键,所以第一个问题的答案是否定的
OwnerId
应自动识别为Owner
的外键,除非映射到外键名称不同的现有数据库。在这种情况下,您可以使用例如:
public abstract class Document: BaseEntity
{
public bool IsActive { get; set; }
public string Description { get; set; }
[Column("UserId"), ForeignKey("Owner")]
public Guid OwnerId { get; set; }
public User Owner { get; set; }
}
可能不需要外键数据注释,但可以使用它将FK属性与导航属性显式配对
在fluent mapping中,您可以使用:
modelBuilder.Entity<Document>()
.Property(d => d.OwnerId)
.HasColumnName("UserId");
modelBuilder.Entity<Document>()
.HasRequired(d => d.Owner)
.WithMany(...)
.HasForeignKey(d => d.OwnerId);
modelBuilder.Entity()
.Property(d=>d.OwnerId)
.HasColumnName(“用户ID”);
modelBuilder.Entity()
.HasRequired(d=>d.Owner)
.有很多(…)
.HasForeignKey(d=>d.OwnerId);
因此,我的验证必须寻找重复的实体,对吗?从业务概念来看,这是有意义的,因为并非所有系统都需要该需求。和往常一样,回答得很好!有关使用验证使密钥属性唯一的示例,请参见。