簡體   English   中英

實體框架代碼優先遷移因更新數據庫而失敗

[英]Entity Framework code-first migration fails with update-database

我首先是新的EF代碼。 我從https://docs.microsoft.com/tr-tr/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/migrations-and-deployment-with-the-entity學習-framework-in-asp-net-mvc-application當我編寫更新數據庫時,出現以下錯誤:

指定“ -Verbose”標志以查看應用於目標數據庫的SQL語句。 應用顯式遷移:[201806161013068_ColumnFirstName]。 應用顯式遷移:201806161013068_ColumnFirstName。 警告:更改對象名稱的任何部分都可能會破壞腳本和存儲過程。 運行種子方法。 System.Reflection.TargetException:非靜態方法需要一個目標。 在System.Reflection.RuntimeMethodInfo.CheckConsistency(對象目標)
在System.Reflection.RuntimeMethodInfo.Invoke(對象obj,BindingFlags invokeAttr,活頁夾活頁夾,Object []參數,CultureInfo文化)在System.Reflection.RuntimeMethodInfo.Invoke(對象obj,BindingFlags invokeAttr,活頁夾活頁夾,Object []參數,CultureInfo文化)
在System.Data.Entity的System.Reflection.RuntimePropertyInfo.GetValue(對象obj,Object []索引)處,在System.Reflection.RuntimePropertyInfo.GetValue(對象obj,BindingFlags invokeAttr,活頁夾活頁夾,Object []索引,CultureInfo文化)處。 System.Data.Entity.Core處的Core.Objects.ELinq.QueryParameterExpression.TryGetFieldOrPropertyValue(MemberExpression me,Object instance,Object&memberValue)System.Data.Entity.Core處的Object.ELinq.QueryParameterExpression.TryEvaluatePath(Expression expression,ConstantExpression&constantExpression) System.Data.Entity.Core.Objects.ObjectQuery 1 forMergeOption) at System.Data.Entity.Core.Objects.ObjectQuery .Objects.ELinq.QueryParameterExpression.EvaluateParameter(Object []參數)在System.Data.Entity.Core.Objects.ObjectQuery 1 forMergeOption) at System.Data.Entity.Core.Objects.ObjectQuery (<Nullable 1 forMergeOption) at System.Data.Entity.Core.Objects.ObjectQuery > System.Dat中的System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction [T]中的c__DisplayClass7.b__6()(功能1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) at System.Data.Entity.Core.Objects.ObjectQuery 1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) at System.Data.Entity.Core.Objects.ObjectQuery 1。<> c__DisplayClass7.b__5()在System.Data.Entity.Infrastructure.DbExecutionStrategy.Execute [TResult](Func 1 operation) at System.Data.Entity.Core.Objects.ObjectQuery 1. 1 forMergeOption) at System.Data.Entity.Core.Objects.ObjectQuery獲取GetResults(Nullable 1 forMergeOption) at System.Data.Entity.Core.Objects.ObjectQuery 1.MoveNext() at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable 1 forMergeOption) at System.Data.Entity.Core.Objects.ObjectQuery GetEnumerator> b__0() 1.MoveNext() at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable 1個源)在System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.b__2 [TResult](IEnumerable的1 sequence) at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute [TResult](表達式表達式),位於System.Data.Entity.Internal.Linq的1 sequence) at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable 1查詢,表達式queryRoot)。 System.Linq.Queryable.SingleOrDefault [TSource](可查詢1 source)
at ContosoUniversity.Migrations.Configuration.Seed(SchoolContext context) in C:\\Users\\Bengisu\\source\\repos\\ContosoUniversity\\ContosoUniversity\\Migrations\\Configuration.cs:line 119 at System.Data.Entity.Migrations.DbMigrationsConfiguration
DbQueryProvider.Execute [TResult](表達式表達式1 source)
at ContosoUniversity.Migrations.Configuration.Seed(SchoolContext context) in C:\\Users\\Bengisu\\source\\repos\\ContosoUniversity\\ContosoUniversity\\Migrations\\Configuration.cs:line 119 at System.Data.Entity.Migrations.DbMigrationsConfiguration
1 source)
at ContosoUniversity.Migrations.Configuration.Seed(SchoolContext context) in C:\\Users\\Bengisu\\source\\repos\\ContosoUniversity\\ContosoUniversity\\Migrations\\Configuration.cs:line 119 at System.Data.Entity.Migrations.DbMigrationsConfiguration
1 source)
at ContosoUniversity.Migrations.Configuration.Seed(SchoolContext context) in C:\\Users\\Bengisu\\source\\repos\\ContosoUniversity\\ContosoUniversity\\Migrations\\Configuration.cs:line 119 at System.Data.Entity.Migrations.DbMigrationsConfiguration
1.OnSeed( DbContext上下文)位於System.Data.Entity.Migrations.DbMigrator.SeedDatabase()位於System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.SeedDatabase()位於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.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable
1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable
1endingMigrations,字符串targetMigrationId,字符串lastMigrationId)

在System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)在System.Data.Entity.Migrations.DbMigrator。<> c__DisplayClasse.b__d()在System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(操作mustSucceededToKeepDatabase)在System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(操作mustSucceedToKeepDatabase)在System.Data.Entity.Migrations.DbMigrator.Update(字符串targetMigration)在System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(字符串System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()的System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()的非靜態方法需要一個目標。

在第119行,

var eInDb = context.Enrollments.Where(s => s.Student.ID == e.Student.ID
                  && s.Course.CourseID == e.CourseID).SingleOrDefault();

我的Configuration.cs:

internal sealed class Configuration : DbMigrationsConfiguration<ContosoUniversity.Data_Access_Layer.SchoolContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(SchoolContext 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.
            var students = new List<Student>
            {
                new Student { FirstMidName = "Carson",   LastName = "Alexander",
                    EnrollmentDate = DateTime.Parse("2010-09-01") },
                new Student { FirstMidName = "Meredith", LastName = "Alonso",
                    EnrollmentDate = DateTime.Parse("2012-09-01") },
                new Student { FirstMidName = "Arturo",   LastName = "Anand",
                    EnrollmentDate = DateTime.Parse("2013-09-01") },
                new Student { FirstMidName = "Gytis",    LastName = "Barzdukas",
                    EnrollmentDate = DateTime.Parse("2012-09-01") },
                new Student { FirstMidName = "Yan",      LastName = "Li",
                    EnrollmentDate = DateTime.Parse("2012-09-01") },
                new Student { FirstMidName = "Peggy",    LastName = "Justice",
                    EnrollmentDate = DateTime.Parse("2011-09-01") },
                new Student { FirstMidName = "Laura",    LastName = "Norman",
                    EnrollmentDate = DateTime.Parse("2013-09-01") },
                new Student { FirstMidName = "Nino",     LastName = "Olivetto",
                    EnrollmentDate = DateTime.Parse("2005-08-11") }
            };
            students.ForEach(s => context.Students.AddOrUpdate(p => p.LastName, s));
            context.SaveChanges();

            var courses = new List<Course>
            {
                new Course {CourseID = 1050, Title = "Chemistry",      Credits = 3, },
                new Course {CourseID = 4022, Title = "Microeconomics", Credits = 3, },
                new Course {CourseID = 4041, Title = "Macroeconomics", Credits = 3, },
                new Course {CourseID = 1045, Title = "Calculus",       Credits = 4, },
                new Course {CourseID = 3141, Title = "Trigonometry",   Credits = 4, },
                new Course {CourseID = 2021, Title = "Composition",    Credits = 3, },
                new Course {CourseID = 2042, Title = "Literature",     Credits = 4, }
            };
            courses.ForEach(s => context.Courses.AddOrUpdate(p => p.Title, s));
            context.SaveChanges();

            var enrollments = new List<Enrollment>
            {
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Alexander").ID,
                    CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID,
                    Grade = Grade.A
                },
                 new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Alexander").ID,
                    CourseID = courses.Single(c => c.Title == "Microeconomics" ).CourseID,
                    Grade = Grade.C
                 },
                 new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Alexander").ID,
                    CourseID = courses.Single(c => c.Title == "Macroeconomics" ).CourseID,
                    Grade = Grade.B
                 },
                 new Enrollment {
                     StudentID = students.Single(s => s.LastName == "Alonso").ID,
                    CourseID = courses.Single(c => c.Title == "Calculus" ).CourseID,
                    Grade = Grade.B
                 },
                 new Enrollment {
                     StudentID = students.Single(s => s.LastName == "Alonso").ID,
                    CourseID = courses.Single(c => c.Title == "Trigonometry" ).CourseID,
                    Grade = Grade.B
                 },
                 new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Alonso").ID,
                    CourseID = courses.Single(c => c.Title == "Composition" ).CourseID,
                    Grade = Grade.B
                 },
                 new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Anand").ID,
                    CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID
                 },
                 new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Anand").ID,
                    CourseID = courses.Single(c => c.Title == "Microeconomics").CourseID,
                    Grade = Grade.B
                 },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Barzdukas").ID,
                    CourseID = courses.Single(c => c.Title == "Chemistry").CourseID,
                    Grade = Grade.B
                 },
                 new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Li").ID,
                    CourseID = courses.Single(c => c.Title == "Composition").CourseID,
                    Grade = Grade.B
                 },
                 new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Justice").ID,
                    CourseID = courses.Single(c => c.Title == "Literature").CourseID,
                    Grade = Grade.B
                 }
            };

            foreach(Enrollment e in enrollments)
            {
                var eInDb = context.Enrollments.Where(s => s.Student.ID == e.Student.ID
                  && s.Course.CourseID == e.CourseID).SingleOrDefault();

                //if the enrollment is not found in the database
                if (eInDb == null)
                {
                    context.Enrollments.Add(e);
                }
            }
            context.SaveChanges();
        }
    }
}

使用-verbose選項:

PM>更新數據庫–使用Startup項目'ContosoUniversity'詳細介紹。 使用NuGet項目“ ContosoUniversity”。 指定“ -Verbose”標志以查看應用於目標數據庫的SQL語句。 目標數據庫是:“ ContosoUniversity2”(數據源:(LocalDb)\\ v11.0,提供程序:System.Data.SqlClient,來源:配置)。 沒有待處理的顯式遷移。 運行種子方法。 System.Reflection.TargetException:非靜態方法需要一個目標。 在System.Reflection.RuntimeMethodInfo.CheckConsistency(對象目標)
在System.Reflection.RuntimeMethodInfo.Invoke(對象obj,BindingFlags invokeAttr,活頁夾活頁夾,Object []參數,CultureInfo文化)在System.Reflection.RuntimeMethodInfo.Invoke(對象obj,BindingFlags invokeAttr,活頁夾活頁夾,Object []參數,CultureInfo文化)
在System.Data.Entity的System.Reflection.RuntimePropertyInfo.GetValue(對象obj,Object []索引)處,在System.Reflection.RuntimePropertyInfo.GetValue(對象obj,BindingFlags invokeAttr,活頁夾活頁夾,Object []索引,CultureInfo文化)處。 System.Data.Entity.Core處的Core.Objects.ELinq.QueryParameterExpression.TryGetFieldOrPropertyValue(MemberExpression me,Object instance,Object&memberValue)System.Data.Entity.Core處的Object.ELinq.QueryParameterExpression.TryEvaluatePath(Expression expression,ConstantExpression&constantExpression) System.Data.Entity.Core.Objects.ObjectQuery 1 forMergeOption) at System.Data.Entity.Core.Objects.ObjectQuery .Objects.ELinq.QueryParameterExpression.EvaluateParameter(Object []參數)在System.Data.Entity.Core.Objects.ObjectQuery 1 forMergeOption) at System.Data.Entity.Core.Objects.ObjectQuery (<Nullable 1 forMergeOption) at System.Data.Entity.Core.Objects.ObjectQuery > System.Dat中的System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction [T]中的c__DisplayClass7.b__6()(功能1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) at System.Data.Entity.Core.Objects.ObjectQuery 1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) at System.Data.Entity.Core.Objects.ObjectQuery 1。<> c__DisplayClass7.b__5()在System.Data.Entity.Infrastructure.DbExecutionStrategy.Execute [TResult](Func 1 operation) at System.Data.Entity.Core.Objects.ObjectQuery 1. 1 forMergeOption) at System.Data.Entity.Core.Objects.ObjectQuery獲取GetResults(Nullable 1 forMergeOption) at System.Data.Entity.Core.Objects.ObjectQuery 1.MoveNext() at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable 1 forMergeOption) at System.Data.Entity.Core.Objects.ObjectQuery GetEnumerator> b__0() 1.MoveNext() at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable 1個源)在System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.b__2 [TResult](IEnumerable的1 sequence) at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute [TResult](表達式表達式),位於System.Data.Entity.Internal.Linq的1 sequence) at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable 1查詢,表達式queryRoot)。 System.Linq.Queryable.SingleOrDefault [TSource](可查詢1 source)
at ContosoUniversity.Migrations.Configuration.Seed(SchoolContext context) in C:\\Users\\Bengisu\\source\\repos\\ContosoUniversity\\ContosoUniversity\\Migrations\\Configuration.cs:line 119 at System.Data.Entity.Migrations.DbMigrationsConfiguration
DbQueryProvider.Execute [TResult](表達式表達式1 source)
at ContosoUniversity.Migrations.Configuration.Seed(SchoolContext context) in C:\\Users\\Bengisu\\source\\repos\\ContosoUniversity\\ContosoUniversity\\Migrations\\Configuration.cs:line 119 at System.Data.Entity.Migrations.DbMigrationsConfiguration
1 source)
at ContosoUniversity.Migrations.Configuration.Seed(SchoolContext context) in C:\\Users\\Bengisu\\source\\repos\\ContosoUniversity\\ContosoUniversity\\Migrations\\Configuration.cs:line 119 at System.Data.Entity.Migrations.DbMigrationsConfiguration
1 source)
at ContosoUniversity.Migrations.Configuration.Seed(SchoolContext context) in C:\\Users\\Bengisu\\source\\repos\\ContosoUniversity\\ContosoUniversity\\Migrations\\Configuration.cs:line 119 at System.Data.Entity.Migrations.DbMigrationsConfiguration
1.OnSeed( DbContext上下文)位於System.Data.Entity.Migrations.DbMigrator.SeedDatabase()位於System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.SeedDatabase()位於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.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable
1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable
1endingMigrations,字符串targetMigrationId,字符串lastMigrationId)

在System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)在System.Data.Entity.Migrations.DbMigrator。<> c__DisplayClasse.b__d()在System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(操作mustSucceededToKeepDatabase)在System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(操作mustSucceedToKeepDatabase)在System.Data.Entity.Migrations.DbMigrator.Update(字符串targetMigration)在System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(字符串System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()的System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()的非靜態方法需要一個目標。

正在收到此特定錯誤。 原來是種子數據中有關用戶創建的代碼。

請密切注意ApplicationUser.UserName我用破折號表示它無法創建用戶。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM