entity-framework - 如何解决此实体框架验证异常?
问题描述
我收到一个验证异常,该异常仅在我的 Web 应用程序运行时发生,而不是在使用 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: : 角色“BaseThing”引用的类型中没有定义名称为“DifferentId”的属性。DifferentId: : 角色“BaseThing”引用的类型中没有定义名称为“DifferentId”的属性。
我尝试将该属性移至基类,将其从子类中删除,并更新子类,但这会导致其他事情向南移动,例如 FK 违规。我沿着那条小路走了一段时间,但什么都做不了。
我们使用的是 EF 6.2。
如果有人有任何想法,我很想听听他们的意见。希望我的代码示例有意义。提前致谢。
解决方案
想通了这一点,并且对解决方案感到有些尴尬。结果我们的解决方案中引用实体框架的两个项目没有引用相同的版本。一个包含我们的 IoC 引导,引用 6.0,另一个包含实际的 EF 相关类(DbContexts、EntityConfigurations),引用 6.2。两者都在引用属性中读取“6.0.0.0”,所以它被忽略了。一旦我将以前的项目更新到 6.2,问题就消失了。
推荐阅读
- css - 即使安装了所有东西,如何解决引导程序不起作用的问题?
- python-3.x - 词形还原嵌套列表中的单词
- android - 伙计们,我正在用颤振编码一些东西,我从变量中取 null 你能帮我吗
- javascript - 车道分配算法
- html - 正确的结构未在 Html Display Flex 上显示
- javascript - 基于技能指数从 10 人列表中组成两个团队的算法
- bash - 将 xargs 与 cat 和 grep 结合使用
- node.js - 如何将 API 调用响应存储为对象或将数组解析为 JSON?
- docker - 具有自动缩放功能的 ECS 集群中的 RabbitMQ
- graphql - 深度合并片段