简体   繁体   English

MVC5数据库中已经有一个名为“ AspNetUsers”的对象

[英]MVC5 There is already an object named 'AspNetUsers' in the database

I'm trying to clone a MVC5 with Identity Roles and Authorize from this tutorial and the project is here . 我正在尝试从本教程中克隆具有身份角色的MVC5并进行授权,并且该项目位于此处

I'm trying to use update-database in my Package Manager Console but it keeps saying I have 我正在尝试在Package Manager控制台中使用update-database ,但一直说我有

There is already an object named 'AspNetUsers' in the database. 数据库中已经有一个名为“ AspNetUsers”的对象。

But if you look in the image I don't have a database that has those tables. 但是,如果您查看图像,则我没有包含这些表的数据库。

WebConfig connectionstring WebConfig连接字符串

<add name="DefaultConnection" connectionString="Data Source=.\\SQLEXPRESS;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" providerName="System.Data.SqlClient" />

在此处输入图片说明

在此处输入图片说明

PM> Update-Database 
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying explicit migrations: [201603280555304_InitialCreate].
Applying explicit migration: 201603280555304_InitialCreate.
System.Data.SqlClient.SqlException (0x80131904): There is already an object named 'AspNetUsers' in the database.
   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 asyncWrite)
   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(DbTransaction transaction, MigrationStatement migrationStatement, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbTransaction transaction, 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, XDocument targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)
   at System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
   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:2640ae66-2469-42f1-92ad-2895d26f73e4
Error Number:2714,State:6,Class:16
There is already an object named 'AspNetUsers' in the database.

Configuration.cs(Seed Method) Configuration.cs(种子方法)

namespace RecreationalServicesTicketingSystem.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;
    using RecreationalServicesTicketingSystem.Models;
    using System.Collections.Generic;

    internal sealed class Configuration : DbMigrationsConfiguration<RecreationalServicesTicketingSystem.Models.ApplicationDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(ApplicationDbContext context)
        {
            var departments = new List<Department>
            {
                new Department { DepartmentID = 1, DepartmentName = "IT"},
                new Department { DepartmentID = 2, DepartmentName = "Menzit Admin" },
                new Department { DepartmentID = 3, DepartmentName = "Human Resources"},
                new Department { DepartmentID = 4, DepartmentName = "Mechanics" },
                new Department { DepartmentID = 5, DepartmentName = "Directors" },
                new Department { DepartmentID = 6, DepartmentName = "Operations"}

            };
            departments.ForEach(s => context.Departments.AddOrUpdate(p => p.DepartmentName, s));
            context.SaveChanges();


            var depots = new List<Depot>
            {
                new Depot { DepotID = 1, DepotName = "Porana"},
                new Depot { DepotID = 2, DepotName = "Far North"},
                new Depot { DepotID = 3, DepotName = "Horowhenua"},
                new Depot { DepotID = 4, DepotName = "Manawatu"},
                new Depot { DepotID = 5, DepotName = "Silverdale"},
                new Depot { DepotID = 6, DepotName = "Christchurch"},

            };
            depots.ForEach(s => context.Depots.AddOrUpdate(p => p.DepotName, s));
            context.SaveChanges();

            var users = new List<ApplicationUser>
        {
            new ApplicationUser { FirstMidName = "Jason",   LastName = "Wan",
                EnrollmentDate = DateTime.Parse("2016-02-18"), DepartmentID = 1, DepotID = 1,IsAdministrator = true},
            new ApplicationUser { FirstMidName = "Andy", LastName = "Domagas",
                EnrollmentDate = DateTime.Parse("2016-02-18"), DepartmentID = 1,DepotID = 1,IsAdministrator = true},
            new ApplicationUser { FirstMidName = "Denis",   LastName = "Djohar",
                EnrollmentDate = DateTime.Parse("2016-02-18"), DepartmentID = 1 ,DepotID = 1,IsAdministrator = true },
            new ApplicationUser { FirstMidName = "Christine",   LastName = "West",
                EnrollmentDate = DateTime.Parse("2016-02-18"), DepartmentID = 2, DepotID = 3,IsAdministrator = false},

        };


            users.ForEach(s => context.Users.AddOrUpdate(p => p.FirstMidName, s));
            context.SaveChanges();

            users.ForEach(s => context.Users.AddOrUpdate(p => p.LastName, s));
            context.SaveChanges();




            var categories = new List<Category>
            {
                new Category {CategoryID = 0001, CategoryName = "Desktop"},
                new Category {CategoryID = 0002, CategoryName = "Mobile"},
                new Category {CategoryID = 0003, CategoryName = "Menzits"},
                new Category {CategoryID = 0004, CategoryName = "XMPRO"},
                new Category {CategoryID = 0005, CategoryName = "Con-X"},
                new Category {CategoryID = 0006, CategoryName = "Promapp"},
                new Category {CategoryID = 0007, CategoryName = "QGIS"},
            };
            categories.ForEach(s => context.Categories.AddOrUpdate(p => p.CategoryName, s));
            context.SaveChanges();

            var tickets = new List<Ticket>
            {
                new Ticket {
                    UserID = users.Single(s => s.LastName == "Wan").Id, //UserID
                    CategoryID = categories.Single(c => c.CategoryName == "Con-X" ).CategoryID,
                    Issue = ("Con-X Login Error"),
                    Priority = Priority.High
                },
                new Ticket {
                    UserID = users.Single(s => s.LastName == "Wan").Id, //UserID
                    CategoryID = categories.Single(c => c.CategoryName == "Desktop" ).CategoryID,
                    Issue = ("Can't remote access C0123"),
                    Priority = Priority.Med
                },
            };


            foreach (Ticket e in tickets)
            {
                var ticketInDataBase = context.Tickets.Where(
                    s =>
                        s.User.Id == e.UserID && //UserID
                        s.Category.CategoryID == e.CategoryID).SingleOrDefault();
                if (ticketInDataBase == null)
                {
                    context.Tickets.Add(e);
                }
            }
            context.SaveChanges();
        }
    }
}

You DO have a database with an AspNetUsers table in your SQL Express database. 您的SQL Express数据库中AspNetUsers有一个带有AspNetUsers表的数据库。 The screenshot you are showing is for a different instance of SQL Server than where your connection string is accessing. 您显示的屏幕快照与连接字符串访问所在的SQL Server实例不同。

  • Screenshot: (localdb)\\MSSqlLocalDb 截图: (localdb)\\MSSqlLocalDb
  • Connection string: .\\SQLExpress (which is the equivalent of (local)\\SQLExpress ) 连接字符串: .\\SQLExpress (与(local)\\SQLExpress等效)

Also, as LoLeRji pointed out, you haven't specified a database name in your connection string. 此外,正如LoLeRji所指出的那样,您尚未在连接字符串中指定数据库名称。 Therefore, your tables will be created in the default database on the server instance (usually the master database). 因此,将在服务器实例上的默认数据库(通常是master数据库)中创建表。

You should always make sure your connection string follows one of the 2 patterns before adding the advanced options (if any). 在添加高级选项(如果有)之前,应始终确保连接字符串遵循两种模式之一。

  • SERVER=<servername\\instancename>;DATABASE=<databasename>;UID=<username>;PWD=<password>;
  • SERVER=<servername\\instancename>;DATABASE=<databasename>;Integrated Security=true;

See: connectionstrings.com 请参阅: connectionstrings.com

I am not so sure this would be of any help, but when I read your connection string, I couldn't see which database you were trying to connect to. 我不确定这是否会有帮助,但是当我阅读您的连接字符串时,我看不到您尝试连接到哪个数据库。 The connection string only states ./SQLEXPRESS as data source, but no database names are given. 连接字符串仅将./SQLEXPRESS声明为数据源,但未提供数据库名称。

For example, as far as I know the connection strings should look like either "data source=<dbserver>;initial catalog=<databasename>;..." or "data source=<path>\\<dbname>;..." . 例如,据我所知,连接字符串应类似于"data source=<dbserver>;initial catalog=<databasename>;...""data source=<path>\\<dbname>;..."

I think the problem is you are trying to update a database but entity framework doesn't know which db to update. 我认为问题是您正在尝试更新数据库,但是实体框架不知道要更新哪个数据库。

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 数据库(ASP.NET MVC)中已经有一个名为“ Accounts”的对象 - Already an object named “Accounts” in the database (ASP.NET MVC) 数据库中已经有一个名为“ Employee”的对象 - There is already an object named 'Employee' in the database 数据库中已经有一个名为“ Reports”的对象 - There is already an object named 'Reports' in the database 数据库中已经有一个名为“ tableName”的对象 - There is already an object named 'tableName' in the database 数据库中已经有一个名为“__MigrationHistory”的对象 - There is already an object named '__MigrationHistory' in the database 如何在 mvc5 中的 AspNetUsers 中添加外键引用 - how to add a foreign key referance in AspNetUsers in mvc5 Update-Database MVC 自动迁移 - 数据库中已经有一个名为“StationsArrangeds”的对象 - Update-Database MVC automatic migrations - There is already an object named 'StationsArrangeds' in the database 创建新的AspNetUsers对象需要ID MVC - Create new AspNetUsers object requires ID MVC 错误“数据库中已经有一个名为&#39;MD&#39;的对象。” - error “There is already an object named 'MD' in the database.” EF 迁移 - 数据库中已经有一个名为“”的对象 - EF Migrations - There is already an object named '' in the database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM