简体   繁体   English

实体框架如何与条件映射?

[英]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个选择:

  • Omit that relationship from the schema and model and create your join(s) when you need them. 从架构和模型中忽略该关系 ,并在需要时创建您的联接。 You also have to keep this in mind when creating the entities that you have to manually set the key values. 创建实体时,还必须牢记这一点,您必须手动设置键值。
  • You could create a nullable column per relationship in the document entity which is supported. 您可以在受支持的document实体中为每个关系创建nullablenullable列。 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM