EntityFramework不保存null和false值 [英] EntityFramework not saving null and false value

查看:132
本文介绍了EntityFramework不保存null和false值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过附加一个断开连接的实体来使用EntityFramework 6更新记录。我想将一个单一的布尔字段更新为 ,但它不起作用。我使用sql server profiler和EF在上下文调用SaveChanges时不生成更新语句。但是,如果我将值设置为 true ,则它将起作用。示例:

I'm trying to update a record using EntityFramework 6 by attaching a disconnected entity. I want to update a single boolean field to false but it doesn't work. I have used sql server profiler and EF doesn't generate an update statement when calling SaveChanges on the context. But if i set the value to true, it works. Example:

这不起作用:

 private void UpdateUser()
 {
    var user = new User { ID = 5 };
    this.Context.Users.Attach(user);

    user.Locked = false;
    this.Context.SaveChanges();
 }

这样做:

 private void UpdateUser()
 {
    var user = new User { ID = 5 };
    this.Context.Users.Attach(user);

    user.Locked = true;
    this.Context.SaveChanges();
 }

我可以通过标记属性修改,如下所示:

I can fix by marking the property as modified like this:

this.Context.Entry(user).Property(e => e.Locked).IsModified = true;

但不明白为什么如果值 true 而不是值为 false 。当尝试将字段设置为null时,有一个类似的问题。

But don't understand why does it work if the value is true and not if the value is false. There is a similar issue when trying to set a field to null.

实体数据模型或数据库可能有问题,但无法弄清楚什么。 p>

There's probably something wrong with the entity data model or database but can't figure out what.

推荐答案

的默认值Boolean code>,所以在附加后设置为 false 不会将属性标记为已更改。

Default value for Boolean is false, so setting to false after attaching won't flag the property as changed.

您可以首先加载实体,然后进行修改,然后保存更改。

You can load the entity first, then do your modifications then save changes.

var user = db.Users.Find(5);
user.Locked = false;
db.SaveChanges();

或者,您可以将要更新的字段的实体附加到布尔字段的不同值

Or you can attach the entity with the field you want to update set to a different value for Boolean fields

var user = new User { Id = 5, Locked = true; };
db.Users.Attach(user);
user.Locked = false;
db.SaveChanges();

这篇关于EntityFramework不保存null和false值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆