0

我正在构建一个 mvc 应用程序,首先使用 EF 代码。我刚开始。这是与我的问题有关的代码。

广告模特

[Key]
     public virtual int ID { get; set; }
     public virtual int UserID { get; set; }
     public virtual int Cycles { get; set; }
     public virtual decimal Cost { get; set; }
     public string Name { get; set; }
     public virtual List<AdDisplayTime> DispalyTime { get; set; }
     public virtual DateTime CreateDate { get; set; }
     public virtual DateTime UpdateDate { get; set; }
     public virtual int UpdatedBy { get; set; }
     public virtual bool FullScreen { get; set; }

AdDisplayTimes 模型

[Key]
public virtual int ID { get; set; }
public virtual int AdID { get; set; }
public virtual string DisplayTime { get; set; }

状态模型

[Key]
public virtual int ID { get; set; }
public virtual string Name { get; set; }

这是我的迁移课程中的种子方法

var adDisplayTimes = new List<AdDisplayTime>
                                 {
                                     new AdDisplayTime{AdID = 1,DisplayTime = "10:30"},
                                     new AdDisplayTime{AdID = 1,DisplayTime = "10:40"},
                                     new AdDisplayTime{AdID = 1,DisplayTime = "10:50"},
                                     new AdDisplayTime{AdID = 1,DisplayTime = "11:00"}
                                 };
        context.Advertisements.AddOrUpdate(a => a.Name,
            new Advertisement
                {
                    Name = "Fisrt Ad",
                    OwnerID = 1,
                    Cycles = 125,
                    Cost = (decimal)234.45,
                    FileName = "test.jpg",
                    Tier = 1,
                    Path = "~/UploadedImages/Pending/test.jpg",
                    DispalyTime = adDisplayTimes,
                    CreateDate = DateTime.Now,
                    ValidFrom = DateTime.Now,
                    ValidTill = DateTime.Now.AddMonths(1),

                    FullScreen = true,
                    IsAdminAd = false,
                    Status = 1
                }
            );
        context.AdDisplayTimes.AddOrUpdate(ad=>ad.AdID,
                                     new AdDisplayTime { AdID = 1, DisplayTime = "10:30" },
                                     new AdDisplayTime { AdID = 1, DisplayTime = "10:40" },
                                     new AdDisplayTime { AdID = 1, DisplayTime = "10:50" },
                                     new AdDisplayTime { AdID = 1, DisplayTime = "11:00" }
            );
        context.Statuses.AddOrUpdate(s=>s.Name,
            new Status{Name = "Pending"},
            new Status{Name = "Approved"},
            new Status{Name = "Edited"},
            new Status{Name = "Activated"},
            new Status{Name = "DeActivated"}
            );

当我从 Visual Studio 中的包管理器控制台运行命令“update-database”时,我得到了这个

update-database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
No pending code-based migrations.
Running Seed method.
System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
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.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
--- End of inner exception stack trace ---
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
--- End of inner exception stack trace ---
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
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()
An error occurred while updating the entries. See the inner exception for details.

请帮我解决这个问题

4

1 回答 1

3

如果您检查内部异常,您会看到此错误

The conversion of a datetime2 data type to a datetime data
 type resulted in an out-of-range value

并且在 SO 中找到的常见解决方案是将 DateTime 列的数据类型定义为 datetime2。您可以使用 Data Annotation 来执行此操作,例如:

[Column(TypeName="datetime2")]

并使用 Fluent Api,例如:

HasColumnType("datetime2")

希望这可以帮助。

于 2012-12-09T06:43:21.673 回答