I have the following tables:
我有以下表格:
Document (Id int PK, LatestVersionId int FK)
DocumentVersion (Id int PK, DocumentId int FK)
document can have one or many versions, meanwhile one version belongs to one document. And I have the following classes:
文档可以有一个或多个版本,同时一个版本属于一个文档。我有以下课程:
public class Document {
public int Id {get;set;}
public int LatestVersionId {get;set;}
public DocumentVersion LatestVersion {get;set;}
}
public class DocumentVersion {
public int Id {get;set;}
public int DocumentId {get;set;}
public Document Document {get;set;}
}
The current mappings:
当前的映射:
HasOptional(t => t.LatestVersion).WithRequired(t => t.Document).Map(t => t.MapKey("DocumentId")) // DocumentMap
HasRequired(t => t.Document).WithOptional(t => t.LatestVersion).Map(t => t.MapKey("LatestVersionId")); // DocumentVersionMap
I'm getting the following exception: System.InvalidOperationException: The navigation property 'Document' declared on type 'DocumentVersion' has been configured with conflicting mapping information.
我收到以下异常:System.InvalidOperationException:在类型'DocumentVersion'上声明的导航属性'Document'已配置了冲突的映射信息。
How should I map such relationships?
我应该如何映射这种关系?
1 个解决方案
#1
Can you update your class definitions as follows:
您可以更新您的类定义,如下所示:
public class Document {
[Key]
public int Id {get;set;}
public List<DocumentVersion> DocumentVersions {get;set;}
}
public class DocumentVersion {
[Key]
public int Id {get;set;}
[ForeignKey("Document")]
public int DocumentId {get;set;}
public Document Document {get;set;}
}
Fluent API:
modelBuilder.Entity<Document>()
.HasMany(d => d.DocumentVersions)
.WithRequired(version => version.Document)
.HasForeignKey(version => version.DocumentId);
#1
Can you update your class definitions as follows:
您可以更新您的类定义,如下所示:
public class Document {
[Key]
public int Id {get;set;}
public List<DocumentVersion> DocumentVersions {get;set;}
}
public class DocumentVersion {
[Key]
public int Id {get;set;}
[ForeignKey("Document")]
public int DocumentId {get;set;}
public Document Document {get;set;}
}
Fluent API:
modelBuilder.Entity<Document>()
.HasMany(d => d.DocumentVersions)
.WithRequired(version => version.Document)
.HasForeignKey(version => version.DocumentId);