实体类型< classname>不是当前上下文模型的一部分 [英] The entity type <classname> is not part of the model for the current context
问题描述
DB有一个表 PackagingInfo
。我有一个包
类,一个 ShopEntities:DbContext
。
$ $ $ $ $ $ $ $ $ $ $ $ $ $
公共十进制PackageID {get;组; }
public decimal Title {get;组; }
public decimal Cost {get;组; }
public bool isFree {get;组;
}
//实体上下文(例如ShopEntities.cs)
public class ShopEntities:DbContext
{
public DbSet<包装及GT;套餐{get;组;
}
//控制器动作(例如HomeController.cs)
public ActionResult Index()
{
ShopEntities _db =新ShopEntities();
var q = _db.Packages.ToList();
return View(q);
}
实例化 _db
上下文并检查其包
属性和异常注意:
实体类型包不是当前上下文的模型的一部分。
更新
问题并要求重新打开,因为情况也发生在模型第一种方法中,其中表格映射在EDMX文件中完成,而不是在此处注明的注释:
模型浏览器窗口显示模型和商店实体类型的bot中的包
,并且实体的表映射显示正确映射到表列的每个属性。这是通过注释代码优先样式完成的相同映射。
明确添加DatabaseGenerated
标识值
[DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]
指定十进制数据类型的精度。这是因为默认情况下,假定十进制数据类型的十进制后面有两个数字。我们需要设置它0。
modelBuilder.Entity< User>()。Property(x => x.ID) .HasPrecision(16,0);
DB has a table PackagingInfo
. I have a Package
class, and a ShopEntities : DbContext
.
// Entity (ex. Package.cs)
[Table("PackagingInfo")]
public class Package
{
public decimal PackageID { get; set; }
public decimal Title { get; set; }
public decimal Cost { get; set; }
public bool isFree { get; set; }
}
// Entity Context (ex. ShopEntities.cs)
public class ShopEntities : DbContext
{
public DbSet<Package> Packages { get; set; }
}
// Controller Action (ex. HomeController.cs)
public ActionResult Index()
{
ShopEntities _db = new ShopEntities();
var q = _db.Packages.ToList();
return View(q);
}
After instantiating the _db
context and inspecting its Packages
property and exception is noticed:
The entity type Package is not part of the model for the current context.
Update
I've edited this question and requested its reopening because the situation is also occuring in a Model first approach where the table mapping is done in the EDMX file instead of the annotation noticed here:
Model Browser window shows the Package
in bot the Model and Store entity types, and the entity's Table Mapping shows each property properly mapped to the table column. This is the same mapping accomplished by the annotation code-first style.
Explicitly add the "DatabaseGenerated"
attribute to set the "identity"
value of the column in database
[DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]
Specify the precision for the decimal data type. This is because by default it assumes there are two numbers after the decimal for decimal data type. We need to set it 0.
modelBuilder.Entity<User>().Property(x => x.ID).HasPrecision(16, 0);
这篇关于实体类型< classname>不是当前上下文模型的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!