简体   繁体   中英

Updating SQL bit column from Entity Framework

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

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.

Here's my update code:

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 'Active' column properties:

EDMX文件中“活动”列的属性。

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM