提问人:Python 提问时间:11/8/2023 最后编辑:Python 更新时间:11/8/2023 访问量:17
EF Core 中多态关系的模型生成器
modelBuilder for Polymorphic Relations in EF Core
问:
我正在尝试进行多态关联,但我的模型构建器无法正常工作
员工类
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 类
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 类
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.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);
}
这是我收到的错误
无法为实体类型配置鉴别器值 “Employee”,因为它不是从“目录”派生的
我希望避免创建从纸张到员工或客户的对象关系
你会给我什么建议?
答: 暂无答案
评论