我正在使用Entity Framework,这里是我的实体模型:
Public class Document
{
Public int Id { get; set; }
Public Document Parent { get; set; }
}正如您所看到的,它有一个self-reference属性。
现在,我尝试添加另一个self-reference属性,如下所示:
Public class Document
{
Public int Id { get; set; }
Public Document Parent { get; set; }
Public Document SrcDocument { get; set; }
}但不幸的是,我遇到了以下错误:
无法确定类型“文档”和“文档”之间关联的主体端。必须使用关系fluent API或数据注释显式地配置此关联的主体端。
发布于 2017-06-21 15:15:55
实体框架Code-First约定假定Document和Document属于相同的关系,是彼此的逆导航属性。因为这两个导航属性都是引用(而不是集合),所以EF推断one-to-one关系。
由于您实际上想要两个one-to-many关系,所以必须重写这些约定。只需重写上下文的OnModelCreating方法,并将您对新循环关系的想法放在这里,如下所示:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Document>().HasRequired(p => p.SrcDocument).WithMany();
base.OnModelCreating(modelBuilder);
}更新
modelBuilder.Entity<Document>().HasRequired(p => p.SrcDocument).WithMany();对实体框架说,SrcDocument与自身有一个one-to-many关系。
您还可以使用以下代码:
modelBuilder.Entity<Document>().HasOptional(p => p.SrcDocument).WithMany();来建立一个zero-to-many关系。
有了这个:
modelBuilder.Entity<Document>().HasOptional(p => p.SrcDocument).WithOptionalDependent();您可以定义一个one-to-zero关系。
会成功的。
发布于 2017-06-22 05:42:20
尝试使用InverseProperty属性:
public class Document
{
public int Id { get; set; }
public virtual Document Parent { get; set; }
public int ParentId { get; set; }
public virtual Document SrcDocument { get; set; }
public int SrcDocumentId { get; set; }
[InverseProperty("Parent")]
public virtual ICollection<Document> Children {get;set;}
[InverseProperty("SrcDocument")]
public virtual ICollection<Document> Derived {get;set;}
}迁移:
CreateTable(
"dbo.Documents",
c => new
{
Id = c.Int(nullable: false, identity: true),
ParentId = c.Int(nullable: false),
SrcDocumentId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Documents", t => t.ParentId)
.ForeignKey("dbo.Documents", t => t.SrcDocumentId)
.Index(t => t.ParentId)
.Index(t => t.SrcDocumentId);https://stackoverflow.com/questions/44679634
复制相似问题