projecten2表”。用户不存在,

时间:2023-01-13 02:16:37

I am experiencing the following error in a C# MVC application using entityFramework:

在使用entityFramework的c# MVC应用程序中,我正在经历以下错误:

System.Data.Entity.Core.EntityCommandExecutionException was unhandled by user code
  HResult=-2146232004
  Message=An error occurred while executing the command definition. See the inner exception for details.
  Source=EntityFramework
  StackTrace:
       at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
       at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
       at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__a()
       at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
       at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__9()
       at System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute[TResult](Func`1 operation)
       at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
       at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
       at System.Lazy`1.CreateValue()
       at System.Lazy`1.LazyInitValue()
       at System.Lazy`1.get_Value()
       at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
       at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
       at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__1[TResult](IEnumerable`1 sequence)
       at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
       at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
       at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
       at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
       at p2groep04.Models.DAL.UserRepository.FindBy(Int32 id) in c:\MyLocation\Models\DAL\UserRepository.cs:line 28
       at p2groep04.Controllers.AccountController.Login(LoginModel model) in c:\MyLocation\Controllers\AccountController.cs:line 53
       at lambda_method(Closure , ControllerBase , Object[] )
       at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
       at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod()
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
       at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
       at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
       at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass48.<InvokeActionMethodFilterAsynchronouslyRecursive>b__41()
  InnerException: MySql.Data.MySqlClient.MySqlException
       HResult=-2147467259
       Message=Table 'projecten2.user' doesn't exist
       Source=MySql.Data
       ErrorCode=-2147467259
       Number=1146
       StackTrace:
            at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
            at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
            at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId)
            at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
            at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
            at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
            at MySql.Data.Entity.EFMySqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
            at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
            at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<>c__DisplayClassb.<Reader>b__8()
            at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TInterceptionContext,TResult](Func`1 operation, TInterceptionContext interceptionContext, Action`1 executing, Action`1 executed)
            at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
            at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
            at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
            at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
       InnerException: 

This is the Context:

这是背景:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using mainNamespace.Models.DAL.Mapper;
using mainNamespace.Models.Domain;
using MySql.Data.Entity;

namespace mainNamespace.Models.DAL
{
    [DbConfigurationType(typeof(MySqlEFConfiguration))]
    public class ProjectContext : DbContext
    {
        public ProjectContext() : base("OurDatabase")
        {
            Database.SetInitializer(new ProjectInitializer());
        }

        public DbSet<Suggestion> Suggestions { get; set; }
        public DbSet<ResearchDomain> ResearchDomains{ get; set; }
        public DbSet<User> Users { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            System.Diagnostics.Debug.WriteLine("TEST");
            modelBuilder.Configurations.Add(new ResearchDomainMapper());
            modelBuilder.Configurations.Add(new SuggestionMapper());
            modelBuilder.Configurations.Add(new UserMapper());
            //modelBuilder.Configurations.Add(new StudentMapper());
            modelBuilder.Ignore<SuggestionState>();

        }
    }
}

The initializer:

初始化:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Linq;
using System.Web;
using mainNamespace.Models.Domain;
using WebMatrix.WebData;

namespace mainNamespace.Models.DAL
{    
    public class ProjectInitializer : DropCreateDatabaseAlways<ProjectContext>
    {

        protected override void Seed(ProjectContext context)
        {            
            try
            {
                context.SaveChanges();


                Console.WriteLine("Database created!");
                System.Diagnostics.Debug.WriteLine("Database created!");
            }
            catch (DbEntityValidationException ex)
            {
                Console.WriteLine("Error");
            }
        }
    }
}

Global asax.cs:

全球asax.cs:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);            
    Database.SetInitializer(new ProjectInitializer());            
    BundleConfig.RegisterBundles(BundleTable.Bundles);

}

User mapper:

用户映射器:

public class UserMapper: EntityTypeConfiguration<User>
    {
        public UserMapper()
        {
            ToTable("user");

            // Primary key
            HasKey(u => u.Id);

            // Properties
            Property(u => u.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).HasColumnName("id");
            Property(u => u.FirstName).HasColumnName("first_name").IsRequired();
            Property(u => u.LastName).HasColumnName("lastname").IsRequired();
            Property(u => u.Email).HasColumnName("email").IsRequired();
            Property(u => u.Salt).HasColumnName("salt").IsRequired();
            Property(u => u.Username).HasColumnName("username").IsRequired();
            Property(u => u.Password).HasColumnName("password").IsRequired();
            Property(u => u.LastLogin).HasColumnName("last_login");
            Property(u => u.LastIp).HasColumnName("last_ip");
            Property(u => u.Role).HasColumnName("role").IsRequired();
        }        
    }

So, i placed some breakpoints and discovered that the Initializer is not being called. Whenever i try to run the application it goes over the context but not over the Initializer. The database is being created but the tables in it not.

因此,我放置了一些断点,并发现初始化器没有被调用。每当我尝试运行应用程序时,它都要经过上下文而不是初始化器。数据库正在创建,但表中没有。

1 个解决方案

#1


1  

I tried around and found a solution, apparently it had something to do with migrations that i had enabled, after deleting the Migrations folder the db created succesfuly.

我尝试了一下,找到了一个解决方案,显然它与我启用的迁移有关,在删除了db创建成功的migrations文件夹之后。

#1


1  

I tried around and found a solution, apparently it had something to do with migrations that i had enabled, after deleting the Migrations folder the db created succesfuly.

我尝试了一下,找到了一个解决方案,显然它与我启用的迁移有关,在删除了db创建成功的migrations文件夹之后。