c# - EF Core 3.1 流畅的 API

标签 c# .net entity-framework asp.net-core-3.1 ef-core-3.1

我有两个实体:

审计类:

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/

相关文章:

entity-framework - Entity Framework 从源代码管理中删除文件

c# - 延迟加载 Entity Framework 5(代码优先)

c# - Entity Framework, Code First, Update独立关联(合集)

c# - 在文本框中显示变量

c# - DDD解决方案结构

.net - 样式 TargetType 属性问题

c# - 关闭/重新打开使用 XML 配置创建的 TraceListener,指向外部 USB 内存棒

c# - 尽管有一个实例,随机变量选择相同的值

c# - 无法在生产 ASP.net 站点上加载文件或程序集 Microsoft.SqlServer.SqlClrProvider,它在哪里?

c# - 总线实例生命周期和最佳实践