将继承的实体添加到DBContext

时间:2017-06-08 15:14:35

标签: c# asp.net-mvc entity-framework

我有这个实体

public class FooEntity
{
   public int ID {get; set;}
   public string Name {get; set;}
}

我需要使用像这样的新字段扩展FooEntity

public class FooExtended : FooEntity
{
  public int Age {get; set;}
}

但我不想在数据库中保留 Age 值,它仅在视图模型中暂时使用。

当我尝试将 FooExtended 的实例添加到DBContext

context.FooEntity.Add(xxx);

我收到以下异常

  

“无法找到EntityType的映射和元数​​据信息   'FooExtended'。“

我尝试将 [NotMapped] 属性添加到 Age 字段中,但我得到了相同的异常。

是否有可能实现我正在尝试使用Entity Framework 6.1.3?

3 个答案:

答案 0 :(得分:0)

context.FooEntity.Add(xxx as FooEntity);

答案 1 :(得分:0)

使用[NotMapped]属性从上下文中排除属性。在这种情况下,您不需要使用继承。您可以阅读更多相关信息HERE

public class FooEntity
{
   public int ID {get; set;}
   public string Name {get; set;}
   [NotMapped]
   public int Age { set; get; }
}

如果你真的坚持这个继承的话,你可以这样做:

context.FooEntity.Add(
    new FooEntity {
      ID = xxx.ID,
      Name = xxx.Name
    }
);

答案 2 :(得分:0)

嗨它似乎是下面任何一个原因都可能导致你的问题。这些是:

   Misspelled properties (case-sensitive!) 

   Properties missing in the POCO class 

   Type mismatches between the POCO and entity-type (e.g.,int instead of long) 

   Enums in the POCO (EF doesn't support enums right now as I understand)

来源:https://stackoverflow.com/a/3439550/3397630

希望它可能会将您重定向到正确的方向

由于

KARTHIK