user3351644
user3351644

Reputation: 41

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). 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)?

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");
    }

Upvotes: 0

Views: 1001

Answers (1)

Igor
Igor

Reputation: 62238

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). You have 2 options:

  • 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. You could add a check constraint in the database to ensure exactly one relationship key has a value (per record).

Upvotes: 1

Related Questions