• Najnowsze pytania
  • Bez odpowiedzi
  • Zadaj pytanie
  • Kategorie
  • Tagi
  • Zdobyte punkty
  • Ekipa ninja
  • IRC
  • FAQ
  • Regulamin
  • Książki warte uwagi

Problem z stworzeniem tabeli po ówczesnym usunięciu jej z bazy.

Object Storage Arubacloud
0 głosów
202 wizyt
pytanie zadane 25 sierpnia 2019 w C# przez Moras Obywatel (1,620 p.)

Zaraz rzucę tym wszystkim w cholerę. Na każdym kroku visual studio wywala mi błędy. Próbuje nauczyć się tworzyć strony w ASP MVC. Zrobiłem sobie:

Context

namespace StoreProject.DAL
{
    using StoreProject.Models;
    using System;
    using System.Data.Entity;
    using System.Linq;

    public class StoreContext : DbContext
    {
        // Your context has been configured to use a 'StoreContext' connection string from your application's 
        // configuration file (App.config or Web.config). By default, this connection string targets the 
        // 'StoreProject.DAL.StoreContext' database on your LocalDb instance. 
        // 
        // If you wish to target a different database and/or database provider, modify the 'StoreContext' 
        // connection string in the application configuration file.
        public StoreContext()
            : base("name=StoreDb")
        {
        }
        static StoreContext()
        {
            Database.SetInitializer<StoreContext>(new StoreInitializer());
        }

        // Add a DbSet for each entity type that you want to include in your model. For more information 
        // on configuring and using a Code First model, see http://go.microsoft.com/fwlink/?LinkId=390109.

         public virtual DbSet<Product> Products { get; set; }
    }

    //public class MyEntity
    //{
    //    public int Id { get; set; }
    //    public string Name { get; set; }
    //}
}

Model klasty product:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace StoreProject.Models
{
    public class Product
    {
        public int ProductId { get; set; }
        [Required(ErrorMessage = "Wprowadź nazwę")]
        public string Name { get; set; }
        public string Country { get; set; }
        [Required(ErrorMessage = "Wprowadź cenę")]
        public float Price { get; set; }
    }

StoreInitializer sobie też zrobiłem:

using StoreProject.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Web;
using StoreProject.Migrations;

namespace StoreProject.DAL
{
    public class StoreInitializer : MigrateDatabaseToLatestVersion<StoreContext, Configuration>
    {
        public static void SeedStoreData(StoreContext context)
        {
            var products = new List<Product>
            {
                new Product(){Name = "Czekolada biała",Price = 2.20f, Country = "Madagaskar"},
                new Product(){Name = "CzekoladaCzarna", Price=3.30f, Country = "Belgia"}
               
            };
            products.ForEach(a => context.Products.AddOrUpdate(a));
          
            context.SaveChanges();
        }
    }
}

Migrację też dodałem:

using StoreProject.DAL;

namespace StoreProject.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    public sealed class Configuration : DbMigrationsConfiguration<StoreProject.DAL.StoreContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
            ContextKey = "StoreProject.DAL.StoreContext";
        }

        protected override void Seed(StoreProject.DAL.StoreContext context)
        {
            StoreInitializer.SeedStoreData(context);
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data.
        }
    }
}

I myślałem, że za każdym razem jak będę uruchamiał aplikację to nie będzie mi dodawało znów tych samych danych, ale tak się nie stało. Postanowiłem usunąć całą tabele z bazy danych z myślą, że jak odpalę to się utworzy znowu tabela Products i mi wstawi tam te dwa produkty, ale wywaliło mi błąd - 

System.Data.Entity.Core.EntityCommandExecutionException
  HResult=0x8013193C
  Message=An error occurred while executing the command definition. See the inner exception for details.
  Source=EntityFramework
  Ślad stosu:
   w System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
   w System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
   w System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__6()
   w System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   w System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()
   w System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   w System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
   w System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
   w System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
   w System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__2[TResult](IEnumerable`1 sequence)
   w System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
   w System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
   w System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
   w System.Data.Entity.Migrations.DbSetMigrationsExtensions.AddOrUpdate[TEntity](DbSet`1 set, IEnumerable`1 identifyingProperties, InternalSet`1 internalSet, TEntity[] entities)
   w System.Data.Entity.Migrations.DbSetMigrationsExtensions.AddOrUpdate[TEntity](IDbSet`1 set, TEntity[] entities)
   w StoreProject.DAL.StoreInitializer.<>c__DisplayClass0_0.<SeedStoreData>b__0(Product a) w C:\Users\krysw\source\repos\StoreWebsite\StoreProject\DAL\StoreInitializer.cs:wiersz 23
   w System.Collections.Generic.List`1.ForEach(Action`1 action)
   w StoreProject.DAL.StoreInitializer.SeedStoreData(StoreContext context) w C:\Users\krysw\source\repos\StoreWebsite\StoreProject\DAL\StoreInitializer.cs:wiersz 23
   w StoreProject.Migrations.Configuration.Seed(StoreContext context) w C:\Users\krysw\source\repos\StoreWebsite\StoreProject\Migrations\Configuration.cs:wiersz 20
   w System.Data.Entity.Migrations.DbMigrationsConfiguration`1.OnSeed(DbContext context)
   w System.Data.Entity.Migrations.DbMigrator.SeedDatabase()
   w System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   w System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
   w System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClasse.<Update>b__d()
   w System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)

Wewnętrzny wyjątek 1:
SqlException: Invalid object name 'dbo.Products'.

Spróbowałem więc użyć komendy "update-database", ale też pojawił się błąd - 

PM> update-database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
No pending explicit migrations.
Running Seed method.
System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Invalid object name 'dbo.Products'.
   w System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   w System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   w System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   w System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   w System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   w System.Data.SqlClient.SqlDataReader.get_MetaData()
   w System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
   w System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
   w System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
   w System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   w System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
   w System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   w System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
   w System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c)
   w System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   w System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
   w System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
   w System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
   w System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
   --- Koniec śladu stosu wyjątków wewnętrznych ---
   w System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
   w System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
   w System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__6()
   w System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   w System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()
   w System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   w System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
   w System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
   w System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
   w System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
   w System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__2[TResult](IEnumerable`1 sequence)
   w System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
   w System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
   w System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
   w System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
   w System.Data.Entity.Migrations.DbSetMigrationsExtensions.AddOrUpdate[TEntity](DbSet`1 set, IEnumerable`1 identifyingProperties, InternalSet`1 internalSet, TEntity[] entities)
   w System.Data.Entity.Migrations.DbSetMigrationsExtensions.AddOrUpdate[TEntity](IDbSet`1 set, TEntity[] entities)
   w StoreProject.DAL.StoreInitializer.<>c__DisplayClass0_0.<SeedStoreData>b__0(Product a) w C:\Users\krysw\source\repos\StoreWebsite\StoreProject\DAL\StoreInitializer.cs:wiersz 23
   w System.Collections.Generic.List`1.ForEach(Action`1 action)
   w StoreProject.DAL.StoreInitializer.SeedStoreData(StoreContext context) w C:\Users\krysw\source\repos\StoreWebsite\StoreProject\DAL\StoreInitializer.cs:wiersz 23
   w StoreProject.Migrations.Configuration.Seed(StoreContext context) w C:\Users\krysw\source\repos\StoreWebsite\StoreProject\Migrations\Configuration.cs:wiersz 20
   w System.Data.Entity.Migrations.DbMigrationsConfiguration`1.OnSeed(DbContext context)
   w System.Data.Entity.Migrations.DbMigrator.SeedDatabase()
   w System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.SeedDatabase()
   w System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   w System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   w System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
   w System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClasse.<Update>b__d()
   w System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   w System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   w System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
   w System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
   w System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()
   w System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
An error occurred while executing the command definition. See the inner exception for details.

O co może chodzić?

1 odpowiedź

0 głosów
odpowiedź 25 sierpnia 2019 przez Moras Obywatel (1,620 p.)
Stworzyłem znów tabele w analogiczny sposób jak usunąłem i działa. Widocznie w podejściu CodeFirst nie mogę grzebać w bazie nie ze strony kody.
komentarz 26 sierpnia 2019 przez pulson666 Stary wyjadacz (12,560 p.)
Dokładnie ;) Jak chcesz grzebać w bazie to wtedy używasz DatabaseFirst.

Podobne pytania

0 głosów
1 odpowiedź 248 wizyt
0 głosów
0 odpowiedzi 148 wizyt
pytanie zadane 25 sierpnia 2019 w C# przez Moras Obywatel (1,620 p.)
0 głosów
1 odpowiedź 243 wizyt
pytanie zadane 2 marca 2020 w C# przez Moras Obywatel (1,620 p.)

92,539 zapytań

141,382 odpowiedzi

319,481 komentarzy

61,928 pasjonatów

Motyw:

Akcja Pajacyk

Pajacyk od wielu lat dożywia dzieci. Pomóż klikając w zielony brzuszek na stronie. Dziękujemy! ♡

Oto polecana książka warta uwagi.
Pełną listę książek znajdziesz tutaj.

Akademia Sekuraka

Kolejna edycja największej imprezy hakerskiej w Polsce, czyli Mega Sekurak Hacking Party odbędzie się już 20 maja 2024r. Z tej okazji mamy dla Was kod: pasjamshp - jeżeli wpiszecie go w koszyku, to wówczas otrzymacie 40% zniżki na bilet w wersji standard!

Więcej informacji na temat imprezy znajdziecie tutaj. Dziękujemy ekipie Sekuraka za taką fajną zniżkę dla wszystkich Pasjonatów!

Akademia Sekuraka

Niedawno wystartował dodruk tej świetnej, rozchwytywanej książki (około 940 stron). Mamy dla Was kod: pasja (wpiszcie go w koszyku), dzięki któremu otrzymujemy 10% zniżki - dziękujemy zaprzyjaźnionej ekipie Sekuraka za taki bonus dla Pasjonatów! Książka to pierwszy tom z serii o ITsec, który łagodnie wprowadzi w świat bezpieczeństwa IT każdą osobę - warto, polecamy!

...