【问题标题】:Seeding my DB with Entity Framework DateTimes使用实体框架日期时间播种我的数据库
【发布时间】:2016-08-08 07:49:36
【问题描述】:

我正在使用带有 Entity Framework 6.1.3 的 Code First 工作流,我正在尝试通过添加如下迁移来为我的数据库植入一些数据:

public partial class SeedDatabaseWithBusinesses : DbMigration
{
    public override void Up()
    {
        Sql("INSERT INTO Businesses (GooglePlaceId, Name, CurrentMenu, LastUpdated)" +
            " VALUES ('googlePlaceIdHere', 'Examples Businesses Name', 'Fish and Chips, BLT, Chicken Sandwich', " + DateTime.UtcNow);
    }

    public override void Down()
    {
    }
}

}

但是我为 DateTime 类型的 LastUpdated 属性输入 DateTime 的方式有问题。当我在 NuGet 中运行 update-database 时,它​​会引发 SQL Server 2016 异常,这表明“语法不正确”。我知道 DateTime 是问题所在,因为异常消息会根据我对 DateTime 条目的操作而改变。 我已经尝试过 DateTime.Now、DateTime.Now.ToString() 和 DateTime.UtcNow,这是我在另一个 StackOverflow 问题上发现的类似但不一样的问题。

我的数据库中的 LastUpdated 值不可为空,因此如果没有此功能,我无法以这种方式为我的数据库播种。任何指导将不胜感激。谢谢。

更新 - 添加了模型和 DbContext:


public class Business
    {
        public int Id { get; set; }
        public string Name { get; set; }
        [Required]
        public string GooglePlaceId { get; set; }
        public DateTime LastUpdated { get; set; }
        public string CurrentMenu { get; set; }
    }

数据库上下文:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public DbSet<Business> Businesses { get; set; }
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }
}

【问题讨论】:

  • 你能发布你的上下文/数据模型吗?
  • 你没有错过一些日期时间的引号吗?像 "...鸡肉三明治', '" + DateTime.UtcNow + "'");不确定,但我会试一试。
  • 顺便说一句,我的疯狂猜测是您可能需要 CASTTO_DATE (无论您喜欢哪个)将 DateTime 值转换为 DateTimestamp (无论您使用哪种类型在 db 列上)
  • 为什么不用你的模型插入数据呢?
  • met.lord 试过了,但它实际上说整个日期仍然是错误的语法。 @uteist 那么数据库列的类型是“日期时间”。我更新了我的上下文和模型

标签: c# sql-server entity-framework datetime


【解决方案1】:

如果要插入当前的 UTC 日期时间值,可以使用 GETUTCDATE() (https://msdn.microsoft.com/en-us/library/ms178635.aspx)。您的查询将如下所示:

INSERT INTO Businesses (GooglePlaceId, Name, CurrentMenu, LastUpdated)
VALUES ('googlePlaceIdHere', 'Examples Businesses Name', 'Fish and Chips', GETUTCDATE());

或者,如果你真的很想用 C# DateTime.Now 进行字符串连接,你可以这样做:

 Sql("INSERT INTO Businesses (GooglePlaceId, Name, CurrentMenu, LastUpdated)" +
     " VALUES ('googlePlaceIdHere', 'Examples Businesses Name', 'Fish and Chips, BLT, Chicken Sandwich', " + DateTime.UtcNow.ToString("yyyy-mm-dd HH:MM:ss"));

【讨论】:

    猜你喜欢
    • 2014-04-30
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    相关资源
    最近更新 更多