c# - EntityFramework 代码优先中的 DateTime 列未按预期工作

标签 c# entity-framework

我有基本模型 User 和两个附加模型 UserCreateModelUserEditModelUserCreateModel 工作正常并创建了用户,但是当我尝试编辑用户时它给我错误。

我不明白他为什么对 datetime 采取行动,因为它在数据库中已经存在有效的 DateTime 属性。我只想更新 Name 属性。我在这里做错了什么?

错误

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. The statement has been terminated.

Controller

public HttpResponseMessage PutUser(int id, UserEditModel user)
{
    if (!ModelState.IsValid)
    {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
    }

    if (id != user.Id)
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }

    db.Entry(user).State = EntityState.Modified;

    try
    {
        db.SaveChanges(); // Exception here, all validation passed with success
    }
    catch (DbUpdateConcurrencyException ex)
    {
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
    }

    return Request.CreateResponse(HttpStatusCode.OK);
}

型号

public class User
{
    public int Id { get; set; }
    public virtual DateTime CreatedDateTime { get; set; }
    public virtual string Username { get; set; }
    public virtual string Password { get; set; }
    public virtual string PasswordSalt { get; set; }
    public virtual string AccessToken { get; set; }
    public virtual string Name { get; set; }
}

public class UserEditModel : User
{
    [Required]
    public override string Name { get; set; }
}

最佳答案

当您将实体映射到数据库时,您需要告诉 Entity Framework 使用正确的列类型。

如果您使用的是 Fluent API,您可以这样做:

Property(p => p.CreatedDateTime).HasColumnType("datetime2");

或者如果您更喜欢直接在 POCO 上使用列属性:

public class User
{   
    public int Id { get; set; }

    [Column(TypeName = "DateTime2")]
    public virtual DateTime CreatedDateTime { get; set; }

    public virtual string Username { get; set; }
    public virtual string Password { get; set; }
    public virtual string PasswordSalt { get; set; }
    public virtual string AccessToken { get; set; }
    public virtual string Name { get; set; }
}

小心;根据您配置 Entity Framework 的方式,您现有的数据库可能会被删除并重新创建以应对更改。

有关更多信息,请参阅以下博客文章:

关于c# - EntityFramework 代码优先中的 DateTime 列未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17513497/

相关文章:

c# - Bootstrap 3 input-group-addon 后缀未附加到表单字段

c# - 如何在 .NET Core 库中记录 Trace?

c# - 如何获取列表集合的增量

c# - Entity Framework 6 : virtual collections lazy loaded even explicitly loaded on a query

c# - 如何使用 OpenXml 在具有多项选择下拉列表的 excel 文件中创建单元格?

C# 等制表符间距

entity-framework - EF 6.1.3 与 "linked server"

entity-framework - MVC 3 EF 4.1 dbContext - 删除具有不可为空的外键关系的一对多数据对象

c# - [DatabaseGenerated(DatabaseGenerationOption.Computed)] 数据注释有什么作用?

c# - Microsoft Entity Framework 中使用的原始 SQL 查询是否返回对象?