Solved

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

Posted on 2016-07-22
7
213 Views
Last Modified: 2016-08-16
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
Comment
Question by:Eduardo Fuerte
  • 4
  • 3
7 Comments
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 41725202
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
 

Author Comment

by:Eduardo Fuerte
ID: 41725835
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
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 41726013
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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 

Author Comment

by:Eduardo Fuerte
ID: 41726477
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
 
LVL 62

Accepted Solution

by:
Fernando Soto earned 500 total points
ID: 41726523
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
 

Author Comment

by:Eduardo Fuerte
ID: 41728253
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
 

Author Closing Comment

by:Eduardo Fuerte
ID: 41757703
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

Featured Post

Control application downtime with dependency maps

Visualize the interdependencies between application components better with Applications Manager's automated application discovery and dependency mapping feature. Resolve performance issues faster by quickly isolating problematic components.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
The viewer will the learn the benefit of plain text editors and code an HTML5 based template for use in further tutorials.
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

912 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now