C#向下转换并添加到实体框架
我有以下课程:C#向下转换并添加到实体框架,c#,entity-framework,casting,C#,Entity Framework,Casting,我有以下课程: class Employee { } class AdvancedEmployee : Employee { } 当我现在尝试添加或编辑员工时,Entity Framework抛出一个异常: AdvancedEmployee ae=new AdvancedEmployee(); db.Employee.Add(ae as Employee); 例外情况是: The entity type AdvancedEmployee is not part of the model f
class Employee { }
class AdvancedEmployee : Employee { }
当我现在尝试添加或编辑员工时,Entity Framework抛出一个异常:
AdvancedEmployee ae=new AdvancedEmployee();
db.Employee.Add(ae as Employee);
例外情况是:
The entity type AdvancedEmployee is not part of the model for the current context.
是否可以“硬”向下转换对象,以便实体框架接受向下转换的
AdvancedEmployee
?您必须映射它。您可以尝试使用AutoMapper或使用我的:
public static class EntityMapper
{
public static void Map(object from, object to)
{
var properties = to.GetType().GetProperties().Where(prop => !Attribute.IsDefined(prop, typeof(NotMappedAttribute)));
foreach (var propertyToMap in properties)
{
var value = propertyToMap.GetValue(from);
propertyToMap.SetValue(to, value);
}
}
}
您可以这样使用:
var baseEmployee = new BaseEmplyee();
Mapper.Map(ae, baseEmployee);
db.Employee.Add(baseEmployee);
您需要创建
Employee
的新实例。感谢您的回复。因为Employee
中有很多属性,而且我很懒,所以我将使用反射。认为有一个更简单(也许更快)的解决方案。不确定您是否可以尝试Employee ae=new AdvancedEmployee(),然后是db.Employee.Add(ae);您应该能够这样做:db.Employee.Add(ae)代码>