Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/277.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# 将继承的实体添加到DBContext_C#_Asp.net Mvc_Entity Framework - Fatal编程技术网

C# 将继承的实体添加到DBContext

C# 将继承的实体添加到DBContext,c#,asp.net-mvc,entity-framework,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;} } 但是我不想在数据库中持久化年龄值,它只在视图的模型中临时使用 当我尝试将FooExtended的实例添加到DBCont

我有这个实体

public class FooEntity
{
   public int ID {get; set;}
   public string Name {get; set;}
}
我需要用这样的新字段扩展FooEntity

public class FooExtended : FooEntity
{
  public int Age {get; set;}
}
但是我不想在数据库中持久化年龄值,它只在视图的模型中临时使用

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

context.FooEntity.Add(xxx);
我得到以下例外

“找不到EntityType的映射和元数据信息 “食物扩展”

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


是否有可能实现我在Entity Framework 6.1.3中尝试的操作?

使用[NotMapped]属性从上下文中排除属性。在这种情况下,您不需要使用继承。你可以阅读更多关于它的内容

context.FooEntity.Add(xxx as FooEntity);
如果您确实坚持这种继承方式,您可以这样做:

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

您好,这似乎是以下任何一个原因都可能导致您的问题。这些是:

   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)
资料来源:

希望它能把你引向正确的方向

谢谢


Karthik

演员阵容是审查队列中的多余部分:请允许我请求您在您的答案周围添加更多的上下文。只有代码的答案很难理解。如果你能在你的文章中添加更多的信息,这将有助于询问者和未来的读者。另请参见。@vClobe演员阵容将隐藏年龄属性。这样,dbContext就不会知道Age属性。请记住,EntityFramework还可以将继承的成员映射到表。这就是异常所说的。我之所以使用继承,是因为我只在特定视图中使用年龄。我尝试将属性[NotMapped]添加到字段年龄,但我得到了相同的异常。我仍然认为正确的方法是将其作为属性包含在FooEntity类中。您仍然可以使其为空(int?)
   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)