Code First EF 保存扩展实体>> 实体类型 xxx 不是当前上下文模型的一部分

Code First EF save extended entity >> The entity type xxx is not part of the model for the current context

提问人:Doe 提问时间:4/17/2018 最后编辑:ChWDoe 更新时间:4/17/2018 访问量:184

问:

我是 EF 的新手。 我扩展了一个实体,其中包含仅在控制器中需要的新属性。
当我保存实体时,我不再需要属性并保存到基本实体并尝试保存,但每次我都收到错误:
upcasted

实体类型 XXX 不是当前上下文模型的一部分。

该属性也不起作用(在类和/或属性上)。[NotMapped]

我怎样才能简单地向上投射并保存实体?

如果我创建一个基本实体的新实例,一切正常。

C# 实体框架 EF 代码优先

评论

1赞 OJ Raqueño 4/17/2018
这是一种常见的情况,其中控制器中使用的类的属性与要保存在数据库中的类的属性不同。最常见的解决方案是不使用继承,而只创建数据库实体的新实例,复制所需的属性。它不仅会为您的特定问题,而且会为其他场景的成功做好准备。
0赞 Doe 4/17/2018
谢谢你的回答。有没有“不那么常见的解决方案”?我的意思是,我如何使用继承并保存基本实体。甚至可能吗?
0赞 DevilSuichiro 4/17/2018
EF 支持 3 种类型的继承。您可以在 entityframeworktutorial.net/code-first/ 上阅读这些内容......
0赞 Ivan Stoev 4/17/2018
不要继承实体(在 EF6 中,它可能会导致其他意外的副作用),而是使用带有包含的 DTO/ViewModel 等。

答:

0赞 Doe 4/17/2018 #1

@Devil,这仅涵盖“向下投射”——我需要“升级”!

我写了一个转换器。我简直不敢相信,我必须这样做',但现在它工作得很好!谢谢,谢谢你的帮助!

public static T ConvertToBase<T>(Object extended) {
  if(extended == null) {
    throw new ArgumentException("Parameter extended was passed null!");
  }

  if(extended.GetType().BaseType != typeof(T)) {
    throw new ArgumentException($"Parameter extended does not inherit base type '{typeof(T).FullName}'");
  }

  PropertyInfo[] baseProperties = extended.GetType().BaseType.GetProperties();
  Object baseInstance = Activator.CreateInstance(extended.GetType().BaseType);

  foreach(PropertyInfo basePropertyInfo in baseProperties) {
    basePropertyInfo.SetValue(baseInstance, basePropertyInfo.GetValue(extended));
  }

  return (T)System.Convert.ChangeType(baseInstance, typeof(T));
}