从实体框架更新SQL位列 [英] Updating SQL bit column from Entity Framework

查看:58
本文介绍了从实体框架更新SQL位列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用C#和Entity Framework更新SQL数据库中的位列时遇到问题。

I'm having an issue updating a 'bit' column in a SQL database, using C# and Entity Framework.

我有一个带有 NOT NULL位列称为活动。当我在表中创建一条记录并将代码中的有效指定为 true或 false时,创建的数据库中的记录是准确的,并且有效列包含了在代码中指定的正确值。当我更新记录并将代码中的有效从假更改为真时,效果也很好。但是,当我更新记录从 true到 false时,数据库中的 Active列仍包含 1(true)。

I have a 'Settings' table with a NOT NULL bit column named 'Active'. When I create a record in the table and specify 'Active' in code as 'true' or 'false', the record in the database that's created is accurate and the 'Active' column contains the correct value that was specified in code. When I update the record and change 'Active' from 'false' to 'true' in code, that works as well. However, when I update the record going from 'true' to 'false', the 'Active' column in the database still contains '1' (true).

是这是一个已知问题?如果是这样,是否有解决方法?我做了很多研究,却找不到任何东西。

Is this a known issue? If so, is there a workaround? I've done a fair amount of research and was unable to find anything.

这是我的更新代码:

public int UpdateSetting(SettingModel settingModel)
{
    using (var db = new EfMyDB())
    {
        // Create a new setting record with the ID of the record to update.
        Setting updatedSetting = new Setting { Id = settingModel.Id };

        // Attach the record.
        db.Settings.Attach(updatedSetting);

        // Update the attached record.
        updatedSetting.Name = settingModel.Name;
        updatedSetting.Value = settingModel.Value;
        updatedSetting.Active= settingModel.Active;

        // Save the database changes.
        return db.SaveChanges();
    }
}

EF有效列属性:

版本 :. NET 4.0,SQL Server 2008,实体框架4.1

Versions: .NET 4.0, SQL Server 2008, Entity Framework 4.1

推荐答案

我认为这是因为创建设置对象时,活动字段采用的是默认值:即false。因此,当您将Active设置为false时,没有任何变化。您必须在更新前从Db加载实体。

I think this is because when you create a Setting object .Active field takes is default value: that is false. So when you set Active to false there is no change. You have to load the entity from the Db before the update.

这篇关于从实体框架更新SQL位列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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