• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1211
  • Last Modified:

How to deal with "Consider using Code First Migrations to update the database" ?

Hi Experts


Could you give me any more assistance on how this ASP NET MVC error must be corrected?

img_ee_001_220716.png
The model backing the 'ProdutoContexto' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).

After reading microsoft article it is still complex and obscure.

Thanks in advance.
0
Eduardo Fuerte
Asked:
Eduardo Fuerte
  • 4
  • 3
1 Solution
 
Fernando SotoRetiredCommented:
I will attempt to help with this question, although is it not my strong point.

What version of Entity Framework are you using?
What type of EF project is this Code First, Model First or Database First?

Basically what the error message is stating is that the database has changed but the model does not reflect the changes.
0
 
Eduardo FuerteAuthor Commented:
Hi

Thanks for your disposition by now:

Relevant parts to clear (I guess)

Entity framework
Here the web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.2.0" newVersion="5.2.2.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <connectionStrings>
    <add name="ConexaoEsportes" connectionString="Data Source=.\sqlexpress;Initial Catalog=ArtigosEsportivos;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

Open in new window


PorutdoContexto.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LojaEsportes.Dominio.Entidades
{
    public class ProdutoContexto : DbContext
    {
         public ProdutoContexto()
            : base("name=ConexaoEsportes")
        { }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            Database.SetInitializer<ProdutoContexto>(new CreateDatabaseIfNotExists<ProdutoContexto>());
        }

        public DbSet<Produto> Produtos { get; set; }
        public DbSet<Categoria> Categoria { get; set; }
    }
}

Open in new window


Where the error ocurs:

using LojaEsportes.Dominio.Entidades;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LojaEsportes.Dominio.Repositorio
{
    public class CategoriaRepositorio : IRepositorio<Categoria>
    {
        private ProdutoContexto context;

        public CategoriaRepositorio(ProdutoContexto produtoContexto)
        {
            this.context = produtoContexto;
        }

        //todas as categorias

       //----- Error ocurs here ---------------
        public IEnumerable<Categoria> GetTodos()
        {
            return context.Categoria.OrderBy(c => c.Nome);
        }

        //retorna uma categoria pelo codigo
        public IEnumerable<Categoria> Get(int? id)
        {
            return context.Categoria.Where(c => c.CategoriaId == id);
        }
    }
}

Open in new window

0
 
Fernando SotoRetiredCommented:
According to your web.config you are using EF 6.0.

Did you create the DbContext and entity classes your self which would be Code first?
Did you create the DbContext and classes by using the wizard with an existing database which would be Database First?
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
Eduardo FuerteAuthor Commented:
The project is a part of a course.

I obtained this project ready but without having the database created.

So I created the database, tables, etc...

The project is gaining content, step by step. In truth several projects, each one gaining complexity to the previous.

The projects 1st to 5th runs very well, without errors but then when I added some other tables to run the 6th project, this error arises.

I guess since the begining it was used FirstDatabase, it's amazing the problem arises when some other tables was added to DB (login and user administration tables).

The error suggest to use CodeFirstMigrations, if possible, could you explain how could it be done?
0
 
Fernando SotoRetiredCommented:
Hi Eduardo;

By the sounds of it you have a Database First approach which means you should have a Entity Framework EDMX designer. Open the designer and right click in an area where there is no object under the cursor and select "Update Model from Database". In the Update Wizard In the Add tab Expand the Tables node and you will find all the tables that are in the database but NOT yet in the model. Select the tables that you added and wish to add to the model in Entity Framework. Then click on the "Finish" button and then re-compile your project.

If you don't have an EF Designer as outlined above then you do have a Code First approach. In that case have a look at this Microsoft whalkthrough, "Code First Migrations", which show how to work with migrations.
0
 
Eduardo FuerteAuthor Commented:
Hi Fernando

Accordingly with information I had elsewhere if anything changes in DB or classes this error arises. So first I carefully check if something had changed, no changes,

After:
Since the project doesn't have EDMX designer I followed the link you suggested. Unfortunatelly almost all the PM commands run in errors I  couln't know the meaning it has.

PM>  Install-Package EntityFramework
Package 'EntityFramework.6.1.3' already exists in project 'LojaEsportes.Web'
PM>  Enable-Migrations 
Exception calling "LoadFrom" with "1" argument(s): "Could not load file or assembly 'file:///C:\LojaEsportesVirtual\packages\EntityFramework.6.1.3\tools\EntityFramework.PowerShell.Utility.dll' or one of its d
ependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)"
At C:\LojaEsportesVirtual\packages\EntityFramework.6.1.3\tools\EntityFramework.psm1:780 char:62
+     $utilityAssembly = [System.Reflection.Assembly]::LoadFrom <<<< ((Join-Path $ToolsPath EntityFramework.PowerShell.Utility.dll))
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException
 
You cannot call a method on a null-valued expression.
At C:\LojaEsportesVirtual\packages\EntityFramework.6.1.3\tools\EntityFramework.psm1:781 char:50
+     $dispatcher = $utilityAssembly.CreateInstance <<<< (
    + CategoryInfo          : InvalidOperation: (CreateInstance:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
 
Exception calling "CreateInstanceFrom" with "8" argument(s): "Could not load file or assembly 'file:///C:\LojaEsportesVirtual\packages\EntityFramework.6.1.3\tools\EntityFramework.PowerShell.dll' or one of its
 dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)"
At C:\LojaEsportesVirtual\packages\EntityFramework.6.1.3\tools\EntityFramework.psm1:809 char:31
+     $domain.CreateInstanceFrom <<<< (
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifi

Open in new window


But at least I had created the dbo._MigrationHistory . I don't know if it could help in something.
img001
Could you check and suggest?
0
 
Eduardo FuerteAuthor Commented:
Hi Fernando

Thank you for your efforts in help me and point a possible solution. I'm still studying how to deal with this problem.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now