Error trying to recreate a table with code first(Migration)

Asked

Viewed 352 times

0

I’m following Eduardo Pires' tutorial on DDD + Asp.Net MVC 5 + Ioc and so on. Well, in the first attempt to create the bank and the client table, it was a gem. It turns out, Eduardo made some changes and I followed (I’m learning from him) and did the same. Well, he then deleted the table and remade it and I did the same. At the time I went (Update-Database -Verbose -Force) is giving me this error and with Eduardo no(I copied all the trace VS2015 generated me)

PM> Update-Database -Verbose -Force
Using StartUp project 'ProjetoModeloDDD.MVC'.
Using NuGet project 'ProjetoModeloDDD.Infra.Data'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'ProjetoModeloDDD' (DataSource: NOTEBOOK_INET\INETSOFTWARE, Provider: System.Data.SqlClient, Origin: Configuration).
No pending explicit migrations.
Applying automatic migration: 201703031708534_AutomaticMigration.
EXECUTE sp_rename @objname = N'dbo.Clientes', @newname = N'Cliente', @objtype = N'OBJECT'
IF object_id('[PK_dbo.Clientes]') IS NOT NULL BEGIN
    EXECUTE sp_rename @objname = N'[PK_dbo.Clientes]', @newname = N'PK_dbo.Cliente', @objtype = N'OBJECT'
END
System.Data.SqlClient.SqlException (0x80131904): Ou o parâmetro @objname é ambíguo ou o @objtype (OBJECT) reivindicado está errado.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
   at System.Data.Entity.Migrations.DbMigrator.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinTransaction(IEnumerable`1 migrationStatements, DbTransaction transaction, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinNewTransaction(IEnumerable`1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection)
   at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClass30.<ExecuteStatements>b__2e()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements, DbTransaction existingTransaction)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, VersionedModel targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)
   at System.Data.Entity.Migrations.DbMigrator.AutoMigrate(String migrationId, VersionedModel sourceModel, VersionedModel targetModel, Boolean downgrading)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.AutoMigrate(String migrationId, VersionedModel sourceModel, VersionedModel targetModel, Boolean downgrading)
   at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
   at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.<Update>b__b()
   at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
   at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
   at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
   at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
ClientConnectionId:edd714ba-f579-4999-bfe6-bdedb5b6240b
Error Number:15248,State:1,Class:11
Ou o parâmetro @objname é ambíguo ou o @objtype (OBJECT) reivindicado está errado.

These are the classes (I removed them using, to decrease the space):

Context

namespace ProjetoModeloDDD.Infra.Data.Contexts
{
    public class ProjetoModeloContext : DbContext
    {
        public ProjetoModeloContext()
            : base("ProjetoModeloDDD")
        {

        }
        public DbSet<Cliente> Clientes { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
            modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
            modelBuilder.Properties()
                .Where(p => p.Name == p.ReflectedType.Name + "Id")
                .Configure(p => p.IsKey());

            modelBuilder.Properties<string>()
                .Configure(p => p.HasColumnType("varchar"));

            modelBuilder.Properties<string>()
                .Configure(p => p.HasMaxLength(100));

            modelBuilder.Configurations.Add(new ClienteConfiguration());
        }
        public override int SaveChanges()
        {
            foreach (var entry in ChangeTracker.Entries().Where(entry => entry.Entity.GetType().GetProperty("DataCadastro") != null))
            {
                if (entry.State == EntityState.Added)
                {
                    entry.Property("DataCadastro").CurrentValue = DateTime.Now;
                }

                if (entry.State == EntityState.Modified)
                {
                    entry.Property("DataCadastro").IsModified = false;
                }
            }


            return base.SaveChanges();
        }
    }
}

Entities

namespace ProjetoModeloDDD.Domain.Entities
{
    public class Cliente
    {
        public int ClienteId { get; set; }
        public string Nome { get; set; }
        public string Sobrenome { get; set; }
        public string Email { get; set; }
        public DateTime DataCadasto { get; set; }
        public bool Ativo { get; set; }

        public bool ClienteEspecial(Cliente cliente)
        {
            return cliente.Ativo && DateTime.Now.Year - cliente.DataCadasto.Year >= 5;
        }
    }
}

Configuration

namespace ProjetoModeloDDD.Infra.Data.EntityConfig
{
    public class ClienteConfiguration : EntityTypeConfiguration<Cliente>
    {
        public ClienteConfiguration()
        {
            HasKey(c => c.ClienteId);

            Property(c => c.Nome)
                .IsRequired()
                .HasMaxLength(150);

            Property(c => c.Sobrenome)
                .IsRequired()
                .HasMaxLength(150);

            Property(c => c.Email)
                .IsRequired();
        }
    }
}
  • places the classes related to that code

  • @Eduardosampaio, I made an edition and put the classes there

  • there is this client table already in your bank?

  • I don’t quite understand, you deleted which table? you are using Migration to do this update?

  • No, @Eduardosampaio, I deleted this table and no longer exists. So, what I don’t understand in the message is that it’s giving the name awareness, but I’ve already deleted it, unless that name is somewhere and Migrations is getting lost there. But where?

  • @Williamcézar, I use Code First to generate the BD and the deleted table is the only one in the project, so far, which is the Client table. Migration will generate the database and tables.

  • You added a new Migration and then gave Update-Database right ? What appeared when you gave the Add-Migration command "Domdomdomigrartion"

  • @Williamcézar, what do you mean a new Migration? I didn’t understand or did something without knowing what I was doing. Can you explain it to me? I thank you.

  • Sorry for the delay, I’ll try to explain it in a quick way, The Add-Migration "Any Name" will add a new Migration with your changes, so when you give the Update-Database it will add this new Migration to your table in the Database (Migration) and make the changes in case there’s nothing wrong. What may be happening and that in your Migration table it still has the reference to your deleted table, so you need to add a new one. Anything I answer properly if that’s the problem.

  • when you add a new Migration it will add what has changed relative to the last and when you update it will make these changes directly in the database. I don’t know if that’s the problem, but it could be.

  • @Williamcézar, man I’m lost. How so new Migration? I don’t get it. I don’t have this command in my code.

  • These commands I do in Nuget, after I have made the changes in my project, I open the Nuget console and type Add-Migration "Domdomnomeration" ai it generates a new class with the changes, and then I give Update-Database and so are the updates.

  • @Williamcézar, what I did was just give a Update-Database -Verbose -Force. That’s what I did, because I followed Eduardo Pires and he did nothing else, at least in his video class. So, what I should really do. As well as the name of the new migration?

  • This Update-Database compando you run where? in the right Nuget Console ?

  • here is some information about Migration and how to use,(https://msdn.microsoft.com/en-us/library/jj591621(v=vs.113).aspx) anything give me the tutorial and I see.

  • Yes, on the Nuget console

  • Then from the Add-Migration Command , soon after it will ask you for a name you will put the name for the change , example Add-Migration removeTabelaCliente, after you give the Update-Database command, at least and this way I do, then he will create a new class of Migrations .

Show 12 more comments

1 answer

-1

Hello! I had the same problem!! I managed to solve by adding in the class

Projectomodelocontext

the using: using System.Linq;

The error I think is generated by the way the code was written using Linq

Browser other questions tagged

You are not signed in. Login or sign up in order to post.