表' projecten2.user'不存在',

时间:2014-04-04 07:20:01

标签: c# entity-framework

我在使用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: 

这是上下文:

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>();

        }
    }
}

初始化程序:

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");
            }
        }
    }
}

全球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);

}

用户映射器:

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();
        }        
    }

所以,我放置了一些断点并发现没有调用初始化程序。每当我尝试运行应用程序时,它都会覆盖上下文但不会超过初始化程序。正在创建数据库,但其中的表没有。

1 个答案:

答案 0 :(得分:1)

我试过并找到了一个解决方案,显然它与我启用的迁移有关,在删除了dbgs创建的Migrations文件夹之后。