提问人:Doe 提问时间:4/17/2018 最后编辑:ChWDoe 更新时间:4/17/2018 访问量:184
Code First EF 保存扩展实体>> 实体类型 xxx 不是当前上下文模型的一部分
Code First EF save extended entity >> The entity type xxx is not part of the model for the current context
问:
我是 EF 的新手。
我扩展了一个实体,其中包含仅在控制器中需要的新属性。
当我保存实体时,我不再需要属性并保存到基本实体并尝试保存,但每次我都收到错误:upcasted
实体类型 XXX 不是当前上下文模型的一部分。
该属性也不起作用(在类和/或属性上)。[NotMapped]
我怎样才能简单地向上投射并保存实体?
如果我创建一个基本实体的新实例,一切正常。
答:
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));
}
评论