简体   繁体   English

EntityFramework代码优先的DateTime列不能按预期工作

[英]DateTime column in EntityFramework code-first does not work as expected

I have base model User and two additional models UserCreateModel and UserEditModel . 我有基本模型User和另外两个模型UserCreateModelUserEditModel UserCreateModel works just fine and user is created, but when I try to edit user it gives me error. UserCreateModel工作正常并且用户已创建,但是当我尝试编辑用户时它会给我错误。

I don't understand why he acts up on datetime since it has valid DateTime property already in place in database. 我不明白他为什么在datetime上行动,因为它在数据库中已经有了有效的DateTime属性。 All I wanted to do is update Name property. 我想要做的就是更新Name属性。 What am I doing wrong here? 我在这做错了什么?

Error 错误

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. 将datetime2数据类型转换为日期时间数据类型会导致超出范围的值。 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);
}

Model 模型

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; }
}

You need to tell Entity Framework to use the correct column type when you map your entities to the database. 在将实体映射到数据库时,需要告诉Entity Framework使用正确的列类型。

If you are using the fluent API you can do it like this: 如果您使用的是流畅的API,您可以这样做:

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

or if you prefer using the column attribute directly on your POCO: 或者如果您希望直接在POCO上使用column属性:

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; }
}

Be careful; 小心; depending on how you have configured Entity Framework, your existing database may be deleted and recreated to account for the change. 根据您配置实体框架的方式,可以删除现有数据库并重新创建以考虑更改。

See the following blog posts for further information: 有关详细信息,请参阅以下博文:

By setting db.Entry(user).State = EntityState.Modified; 通过设置db.Entry(user).State = EntityState.Modified; you tell EF that you want to update all properties of user . 你告诉EF你想要更新user 所有属性。 And because your UserEditModel derives from the User entity EF will try to update all entity properties. 并且因为您的UserEditModel派生自User实体,EF将尝试更新所有实体属性。

I don't know why you derive the Edit model from the entity but it causes problems in your scenario. 我不知道为什么你从实体派生编辑模型,但它会导致你的场景出现问题。 I would prefer to just load the user from the Db, update the property you want and save it: 我更愿意只从Db加载用户,更新你想要的属性并保存它:

var dbUser = db.Users.Find(user.Id);
dbUser.Username = user.Name;
db.SaveChanges();

More generally you can update multiple properties like so: 更一般地,您可以更新多个属性,如下所示:

var dbUser = db.Users.Find(user.Id);
db.Entry(dbUser).CurrentValues.SetValues(user);
db.SaveChanges();

But it requires that the properties in the edit model have the same name as the entity properties (and that the edit model is not derived from the entity). 但它要求编辑模型中的属性与实体属性具有相同的名称(并且编辑模型不是从实体派生的)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在代码优先的EntityFramework中有重复的引用? - Why is there duplication of references in code-first EntityFramework? HOWTO:带有EntityFramework和Code-First的SQLite - HOWTO: SQLite with EntityFramework and Code-First EntityFramework代码优先继承,并渴望在派生类上包含关系 - EntityFramework code-first inheritance with eager include relationship on derived class MVC EntityFramework代码优先迁移-Seed()是否由于DbUpdateException而失败? - MVC EntityFramework Code-First Migrations - Seed() Failing with DbUpdateException? EntityFramework 代码优先迁移忽略 [Key] 并强制使用复合键 - EntityFramework Code-first migration ignoring [Key] and forcing composite key MVC EntityFramework代码优先迁移-Seed()是否由于AmbiguousMatchException而失败? - MVC EntityFramework Code-First Migrations - Seed() Failing with AmbiguousMatchException? MVC EntityFramework代码优先迁移正在执行,但是种子未生效? - MVC EntityFramework Code-First Migration is executing, but Seed not taking effect? 使用 EntityFramework 6 Code-First 播种期间的 IDENTITY_INSERT - IDENTITY_INSERT during seeding with EntityFramework 6 Code-First 使用代码优先和 EntityFramework 6,WFA 的多个 IEntityChangeTracker 实例无法引用实体 object - An entity object cannot be referenced by multiple instances of IEntityChangeTracker using code-first and EntityFramework 6 ,WFA 使用代码优先EntityFramework将ASP WebProject上载到WebHosting-CREATE DATABASE'master' - Upload ASP WebProject to WebHosting with Code-First EntityFramework - CREATE DATABASE 'master'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM