modelBuilder for Polymorphic Relations in EF Core

33 views Asked by At

I'm trying to make a Polymorphic association but my modelBuilder is not working well

Employee Class

public class Employee
{
    public int Id { get; set; } // Unique identifier for the employee
    public ICollection<Directory> Directories { get; set; } // Collection of directories for the employee
}

Client class

public class Client
{
    public int Id { get; set; } // Unique identifier for the client
    public ICollection<Directory> Directories { get; set; } // Collection of directories for the client
}

Directory class

public class Directory
{
    public int Id { get; set; }
    public UserType Type { get; set; } // "Employee"(0) or "Client"(1)
    public int TypeId { get; set; } // Id of the respective Employee or Client
    public string Title { get; set; }
}

modelBuilder

modelBuilder.Entity<Directory>()
            .HasKey(p => p.Id);

        modelBuilder.Entity<Directory>()
            .HasDiscriminator<UserType>("Type")
            .HasValue<Employee>(UserType.Employee)
            .HasValue<Client>(UserType.Client);

        modelBuilder.Entity<Directory>()
            .HasOne<Employee>()
            .WithMany(e => e.Directories)
            .HasForeignKey(p => p.TypeId);

        modelBuilder.Entity<Directory>()
            .HasOne<Client>()
            .WithMany(c => c.Directories)
            .HasForeignKey(p => p.TypeId);
    }

this is the error I get

Cannot configure the discriminator value for entity type 'Employee' because it doesn't derive from 'Directory'

I wouldlike to avoid having to create a object relation from paper to employee or client

What would you suggest me?

0

There are 0 answers