[英]Entity Framework How mapping with condition?
I have three class Student,Teacher and Document. 我有三个班级的学生,教师和文档。 Student and Teacher may have many Documents 学生和老师可能有很多文件
public class BaseEntity
{
public int ItemId { get; set; }
public bool IsDeleted { get; set; }
}
//ParentType Student = 1
public class Student : BaseEntity
{
public string Name { get; set; }
public string Surname { get; set; }
public ICollection<Document> Documents { get; set; }
}
//ParentType Teacher = 2
public class Teacher : BaseEntity
{
public string Name { get; set; }
public string Surname { get; set; }
public ICollection<Document> Documents { get; set; }
}
public class Document
{
public int ParentId { get; set; } //Foreign Key
public int ParentTypeId { get; set; }
}
I use Entity Framework(Fluent API). 我使用实体框架(Fluent API)。 For example, I create map for Student and I don't know how to configure Document in student with two Condition (where parentId = itemId and ParentType = 1)
? 例如,我为学生创建地图,但我不知道如何在学生中配置两个条件(where parentId = itemId and ParentType = 1)
?
public class StudentMap : EntityTypeConfiguration<Student>
{
public StudentMap()
{
ToTable("Student", "dbo");
// Primary Key
HasKey(t => new {t.ItemId});
// Properties
Property(t => t.ItemId).HasColumnName("ItemId");
Property(t => t.IsDeleted)
.IsRequired()
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)
.HasColumnName("IsDeleted");
Property(t => t.Name)
.IsRequired()
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)
.HasColumnName("Name");
Property(t => t.Surname)
.IsRequired()
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)
.HasColumnName("Surname");
}
You can't have a conditional foreign key in EF just like I am pretty sure you can't have one in most DBMSs (like sql server). 就像我非常确定您在大多数DBMS(例如sql server)中没有一个一样,您在EF中不能有条件外键。 You have 2 options: 您有2个选择:
nullable
column per relationship in the document
entity which is supported. 您可以在受支持的document
实体中为每个关系创建nullable
为nullable
列。 You could add a check constraint in the database to ensure exactly one relationship key has a value (per record). 您可以在数据库中添加检查约束,以确保恰好一个关系键具有值(每个记录)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.