Patrik
Patrik

Reputation: 1129

Error Entity Framework Database Changed

I have started with ASP.NET MVC and the Entity Framework recently.

With an existing Database, I tried to map my classes to the database tables. Without success.

Let me show you my database tables:

-> Categories --> Id (PK) --> Title --> Description

-> Products --> Id (PK) --> Name --> Description --> Price --> Category (FK -> CategoryTree)

-> CategoriyTree --> Id (PK) --> ParentCategory (FK -> Category) --> ChildCategory (FK -> Category)

Now, my classes for the Entity Framework:

class Products
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal? Price { get; set; }
    public virtual ICollection<CategoryTree> Category { get; set; }
}

class Categories
{
    public int categoriesId { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
}

class CategoryTree
{
    public int Id { get; set; }
    public virtual ICollection<Categories> ParentCategory { get; set; }
    public virtual ICollection<Categories> ChildCategory { get; set; }
}

class EFDbContext : DbContext
{
    public DbSet<Products> Products { get; set; }
    public DbSet<Categories> Categories { get; set; }
    public DbSet<CategoryTree> CategoryTree { get; set; }
}

If I start the application, the compiler alerts the following error message: The model backing the 'EFDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).

I hope someone can help me to understand this ;-)

Best regards

Upvotes: 0

Views: 530

Answers (3)

Ackroydd
Ackroydd

Reputation: 1610

The only difference I can see from the above information id Categories.Id in the db and Categories.categoriesId in the model (assuming no typo).

Also check the nullability of columns, for example Product.Price is nullable in the model, is it so in the db?

Can I also suggest, generate a new db with a different name from your model and compare to the existing db. The db name is specified in the connection string, so add a constructor to you DbContext class and pass the connection string in,

internal class EFDbContext : DbContext
{
    public EFDbContext(string connectionString) : base(connectionString)
    {

    }

Upvotes: 1

ckal
ckal

Reputation: 3570

In the Application_Start() method of your Global.asax.cs, add the following line:

Database.SetInitializer<EFDbContext>(null);

That will stop Entity Framework from checking for changes to your model since the creation of your database.

Upvotes: 2

J.W.
J.W.

Reputation: 18181

For an existing database, I would suggest use EF power tool to reverse engineering to generate POCO classes.

Upvotes: 1

Related Questions