无法使DateTime.Parse正常工作

时间:2014-02-06 12:44:17

标签: c# sql entity-framework asp.net-mvc-4 datetime

我正在学习如何使用MVC4和Entity Framework,为此我正在学习Contoso大学的教程。在第4章中,我被要求为我的数据库生成种子,但是当我尝试更新它时,PMC向我显示存在错误。

这是其中一个实体:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;    

namespace ContosoUniversityMVC4.Models
{
    public class Student
    {
        public int StudentID { get; set; }

        [StringLength(30, MinimumLength = 3)]
        public string LastName { get; set; }

        [StringLength(30, MinimumLength = 3,  ErrorMessage ="Some error message")]
        [Column("FirstName")]
        public string FirstMidName { get; set; }

        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]    
        public DateTime EnrollmentDate { get; set; }

        public string FullName
        {
            get { return LastName + ", " + FirstMidName; }
        }

        public virtual ICollection<Enrollment> Enrollments { get; set; }

    }
}

这是种子的代码部分,我在其中传递此实体的值:

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

            students.ForEach(s => context.Students.AddOrUpdate(p => p.LastName, s));
            context.SaveChanges();

这是PMC显示的错误:

PM> update-database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying code-based migrations: [201402051617351_Chap4C].
Applying code-based migration: 201402051617351_Chap4C.
Running Seed method.
System.FormatException: String was not recognized as a valid DateTime.
   at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
   at System.DateTime.Parse(String s)
   at ContosoUniversityMVC4.Migrations.Configuration.Seed(SchoolContext context) in c:\Users\f9243821\Documents\Visual Studio 2012\Projects\ContosoUniversityMVC4\ContosoUniversityMVC4\Migrations\Configuration.cs:line 20
   at System.Data.Entity.Migrations.DbMigrationsConfiguration`1.OnSeed(DbContext context)
   at System.Data.Entity.Migrations.DbMigrator.SeedDatabase()
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.SeedDatabase()
   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.Update(String targetMigration)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
   at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()
   at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
String was not recognized as a valid DateTime.

很明显,它无法将我尝试传递的日期转换为有效的DB日期时间格式。我已经检查了数据库,字段类型是“datetime”(yyyy-MM-dd hh:mm:ss.nnn,因为我在手工编辑时也能看到)。 “第20行”是指“var students = new List”,这使我认为我无法正确传递种子的“学生”部分。

我试图更改字符串的值(例如,yyyy-MM-dd hh:mm:ss),或删除de“.Parse”属性并尝试直接传递日期,但到目前为止我无法解决问题。

这段代码是按照本教程的指导原则编写的,因为我不完全理解我在做什么(因为这对我来说是新的,我正在努力学习)。

你可以告诉我我做错了什么吗?如果您需要更多相关信息(VS / SQL版本,更多代码等),请告诉我们。

1 个答案:

答案 0 :(得分:2)

此问题与EF迁移,EF或SQL无关,这与您尝试解析的日期不符合您的应用程序运行的文化格式的事实有关。 Parse将使用当前的系统文化日期格式来尝试解析您的日期字符串,如果它不匹配则抛出FormatException

手动解析日期时,最好使用ParseExact / TryParseExact,这样可以指定您尝试解析的日期的确切格式,例如

EnrollmentDate = DateTime.ParseExact("2013-09-01", "yyyy-MM-dd", CultureInfo.InvariantCulture)