C# “我面临着例外”;AutoFixture.ObjectCreationExceptionWithPath“;在EF核心代码优先的方法中使用AutoFixture

C# “我面临着例外”;AutoFixture.ObjectCreationExceptionWithPath“;在EF核心代码优先的方法中使用AutoFixture,c#,xunit,autofixture,C#,Xunit,Autofixture,我目前正在使用EF核心代码优先的方法,我有以下域类: public class Employee { // several properties such as Name, Address, ... public Guid? CompanyId { get; set; } public Company Company {get;set;} } public class Company { public Guid? CompanyId { get; set; }

我目前正在使用EF核心代码优先的方法,我有以下域类:

public class Employee
{
  // several properties such as Name, Address, ...

  public Guid? CompanyId { get; set; }

  public Company Company {get;set;}

}

 public class Company
{
   public Guid? CompanyId { get; set; }

   public IEnumerable<Employee>? Employee{ get; set; }
}
我需要在Employee类中包含:public Company{get;set;},使其成为外键。但是如果我去掉那条线,它就可以正常工作了

许多在线链接建议以下解决方案-但我想知道是否有其他方法代替删除ThrowingRecursion行为:

fixture.Behaviors.OfType<ThrowingRecursionBehavior>().ToList()
    .ForEach(b => fixture.Behaviors.Remove(b));
fixture.Behaviors.Add(new OmitOnRecursionBehavior());
fixture.Behaviors.OfType().ToList()
.ForEach(b=>fixture.Behaviors.Remove(b));
fixture.Behaviors.Add(新的省略递归行为());

这可能不是您关于如何使用AutoFixture的问题的直接答案。。。有许多可能的选择:

  • 您可以根据问题中的建议自定义AF
  • 您可以配置EF核心外键
  • 或者,您可以将代码设计更改为更DDD风格。这可能会帮助您避免任何AF自定义,但也可能会花费更多的时间
  • 使代码更“DDD ish”的第一步是关闭公共setter,并开始通过构造函数或方法参数管理实体。这将允许AF创建没有循环依赖项的类。EF Core也足够聪明,能够将值设置到受保护的成员中。代码可能如下所示:

    public class Employee
    {
      // closed setter, no AF issues, EF Core will still work
      public Company Company {get; protected set;} 
    
      // Some functionality from your domain model
      public void JoinCompany(Company company)
      {
          // do smth here.
          Company = company
      }
    
      public void LeaveCompany()
      {
          Company = null;
      }
    }
    
    或者,从公司的角度来看,API可能如下所示(同样,我不知道您的域模型,所以只需原型):

    上市公司
    {
    私人名单_employee=新名单();
    公共IReadOnlyCollection员工=>\u员工;
    公开作废登记员工(员工)
    {
    _employee.Add(employee);
    }
    }
    
    以下是一些代码示例:

    fixture.Behaviors.OfType<ThrowingRecursionBehavior>().ToList()
        .ForEach(b => fixture.Behaviors.Remove(b));
    fixture.Behaviors.Add(new OmitOnRecursionBehavior());
    
    public class Employee
    {
      // closed setter, no AF issues, EF Core will still work
      public Company Company {get; protected set;} 
    
      // Some functionality from your domain model
      public void JoinCompany(Company company)
      {
          // do smth here.
          Company = company
      }
    
      public void LeaveCompany()
      {
          Company = null;
      }
    }
    
    public class Company
    {
        private List<Employee> _employee = new List<Employee>();
    
        public IReadOnlyCollection<Employee> Employee => _employee;
    
        public void EnrollEmployee(Employee employee)
        {
            _employee.Add(employee);
        }
    }