具有多个可选一对一关系的实体框架表 [英] Entity Framework table with multiple optional one to one relationships
问题描述
这里有几个问题,但是没有一个对我有太大帮助,所以我决定问自己一个问题。
There are a few questions out there but none of them have been much help to me so I decided to ask my own.
我想先使用Entity Framework代码创建一个奇怪的关系。我有三个实体(资格
,测试
和程序
)所有人都可以选择拥有文件。我正在尝试将所有文档存储在一张表中。如何配置所有这些实体之间的关系。
I want to use Entity Framework code first to create a strange relationship. I have three entities (Qualification
, Test
and Procedure
) that all have the option of having a document(s). I am attempting to store all the documents in one table. How do I configure the relationship between all these entities.
-
资格
有一个一个可选的Document
-
Test
具有一对一的可选文档
-
过程
有一对多的可选Documents
Qualification
has one to one optionalDocument
Test
has one to one optionalDocument
Procedure
has one to many optionalDocuments
文档
与一个<$ c具有必需的关系$ c>资格,测试
或程序
。
public class Assessment
{
public int AssessmentId { get; set; }
//Other properties in Assessment
public Document Document { get; set; }
}
public class Qualification
{
public int QualificationId{ get; set; }
//Other properties in Qualification
public Document Document { get; set; }
}
public class Procedure
{
public int ProcedureId { get; set; }
//Other properties in Procedure
public ICollection<Document> Documents { get; set; }
}
public class Document
{
public int DocumentId { get; set; }
//Other properties in Document
public Qualification Qualification { get; set; }
public Assessment Assessment { get; set; }
public Procedure Procedure { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Not sure what goes here, but this was not working
modelBuilder.Entity<Document>()
.HasOptional(d => d.Qualification).WithOptionalPrincipal(q => q.Document);
modelBuilder.Entity<Document>()
.HasOptional(d => d.Asssessment).WithOptionalPrincipal(q => q.Document);
}
添加迁移时出现错误:
无法确定类型之间关联的主体。必须使用关系流利的API或数据注释来显式配置此关联的主体端。
Unable to determine the principal end of an association between the types. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
我不确定该怎么做这个。我在评估
和资格
中具有可为空的int DocumentId
b / c 过程
可以保存集合,因此 Document
必须保留ID。 Document
是否为每个可能的父项保留一个可为空的ID?
I am not sure how to do this. I had a nullable int DocumentId
in Assessment
and Qualification
but that will not work b/c Procedure
can hold a collection so Document
must hold the Id. Does Document
hold a nullable Id for each possible parent? Help please.
推荐答案
在映射中,您将 Document
设置为主体,但实际上这是依赖的。因此,您应该将映射更改为:
In your mappings you set Document
as principal, but in reality it is the dependent. So you should change your mappings to:
modelBuilder.Entity<Document>()
.HasRequired(d => d.Qualification)
.WithOptionalDependent(q => q.Document);
modelBuilder.Entity<Document>()
.HasRequired(d => d.Asssessment)
.WithOptionalDependent(q => q.Document);
这篇关于具有多个可选一对一关系的实体框架表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!