Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#向下转换并添加到实体框架_C#_Entity Framework_Casting - Fatal编程技术网

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)