[英]Entity framework code first mapping by foreign keys
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? 我应该如何映射这种关系?
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: 流利的API:
modelBuilder.Entity<Document>()
.HasMany(d => d.DocumentVersions)
.WithRequired(version => version.Document)
.HasForeignKey(version => version.DocumentId);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.