我有两个实体:
审计类:
public class Audit
{
public string AuditId{get;set;}
public int EmployeeId{get;set;}
public virtual ModEmployee{get;set;}
}
Employee 类:
public class Employee
{
public int EmployeeId{get;set}
}
加载时 Set<Audit>
,我希望填充 Audit 类的 Employee 属性。
这显然是一对多关系的情况,其中一个审计将有一个员工,但一个员工可以在多个审计中。
我的 Fluent API 如下所示:
protected override OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Audit>()
.HasOne(a=>a.ModEmployee)
.WithMany()
.HasForeignKey("EmployeeId");//a=>a.EmployeeId wont work.
}
我一直在寻找解决方案,并从 this answer 获取了一些信息但它是一对一的。那么this resource展示了一种方法,但这将要求我在 Employee 类中有一组审计。
我无法更改现有模型或添加注释,因为它们已被某些其他 Entity Framework 版本(非核心)使用。
目前我收到以下错误:
System.InvalidOperationException: 'Unable to determine the relationship represented by navigation property 'Employee.ModEmployee' of type 'Employee'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.'
如果我在 Audit 的构建器上添加忽略方法,错误就会消失,如下所示:.Ignore(a=>a.ModEmployee)
但我不会在 Audit 中获取实体对象。任何帮助将不胜感激。我在 EFCore 3.1.10 上。谢谢阅读。
任何帮助将不胜感激。
最佳答案
尝试将 Audit
类中的类型从 int
更改为 Employee
。
应该可以正常工作,因为这是在 Fluent API 中关联外键的正确方法。
PS:FK 属性字符串应与 Employee
中的完全相同,这已经发生了。
关于c# - EF Core 3.1 流畅的 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65778575/