[英]DateTime column in EntityFramework code-first does not work as expected
I have base model User
and two additional models UserCreateModel
and UserEditModel
. 我有基本模型
User
和另外两个模型UserCreateModel
和UserEditModel
。 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? 我在这做错了什么?
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.
该语句已终止。
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; }
}
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.