Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

ef code first - The entity type <classname> is not part of the model for the current context

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...