如何解决此Entity Framework验证异常?

时间:2018-05-16 18:40:05

标签: entity-framework

我收到的验证异常仅在我的网络应用程序运行时发生,但在使用MSTest运行自动化测试时却没有(即使这些测试使用相同的组件)。

相关代码如下:

public abstract class BaseThing
{
  public int Id {get;set;}
  //other properties
}

public class BaseThingConfig :EntityTypeConfiguration<BaseThing>
{
  ToTable("BaseThingTable");
  HasKey(d=>d.Id);
  Property(d=>d.Id).HasColumnName("SomeId");

  Map<ThingChild1>(d=>d.Requires("ThingType").HasValue(1);
  Map<ThingChild2>(d=>d.Requires("ThingType").HasValue(2);
  Map<ThingChild3>(d=>d.Requires("ThingType").HasValue(3);
}

public class ThingChild1 : BaseThing
{
  public long AggregateRootId {get;set;}
  //other stuff
}

    public class ThingChild1Config : EntityTypeConfiguration<ThingChild1>
    {         
Property(d=>d.AggregateRootId).IsRequired().HasColummName("DifferentId");
    }

//the other two child classes of BaseThing and their configs look similar

public class AggregateRoot
{
  public int Id {get;set;}
  public virtual ICollection<ThingChild1> ThingChildren1 {get; private set;}
  public virtual ICollection<ThingChild2> ThingChildren2 {get; private set;}
  public virtual ICollection<ThingChild2> ThingChildren3 {get; private set;}
}

public class AggregateRootConfig : EntityTypeConfiguration<AggregateRoot>
{
  HasMany(d=>d.ThingChildren1).WithRequired().HasForeignKey(a=>a.AggregateRootId);
  HasMany(d=>d.ThingChildren2).WithRequired().HasForeignKey(a=>a.AggregateRootId);
  HasMany(d=>d.ThingChildren3).WithRequired().HasForeignKey(a=>a.AggregateRootId);
}

当我运行使用这些类的代码使用其ID从数据库返回AggregateRoot的实例时,一切运行正常。但是,当我通过我们的Web应用程序运行相同的代码(使用SimpleInjector来播放DbContext)时,当我跳过对dbContext.AggregateRoots.FirstOrDefault(d=>d.Id=id);

的调用时,我得到以下异常
  

在模型生成期间检测到一个或多个验证错误:

     

DifferentId ::没有名称为“DifferentId”的属性   在Role'BaseThing'引用的类型中定义。 DifferentId:   :类型中没有定义名称为“DifferentId”的属性   由角色'BaseThing'引用。

我尝试将该属性移动到基类,从子类中删除它,并更新子类,但这导致其他东西向南移动,如FK违规。我跟着那条路走了一段时间,但是无法做任何事情。

我们正在使用EF 6.2。

如果有人有任何想法,我很乐意听到。希望我的代码示例有意义。提前谢谢。

1 个答案:

答案 0 :(得分:0)

想出这个,并且有点尴尬的解决方案。结果是我们的解决方案中的两个项目引用了实体框架没有引用相同的版本。一个是我们的Io​​C引导容器,引用6.0和另一个容器,它们包含实际的EF相关类(DbContexts,EntityConfigurations),引用了6.2。两者都在引用属性中读取“6.0.0.0”,因此被忽略了。一旦我将之前的项目更新为6.2,问题就消失了。

相关问题