Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 4 - Not always updating boolean property using ApplyCurrentValues

I have a simple entity for a Country that is produced by Entity Framework 4 using VS 2010 RC. It looks something like the POCO below.

public class Company
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string ISOCode { get; set; }
    public boolean Active { get; set; }
}

My repository code is below. 'db' is a my context that is initialized in the constructor.

public void EditCountry(Country countryToEdit)
{
    db.Countries.Attach(new Country { ID = countryToEdit.ID });
    db.Countries.ApplyCurrentValues(countryToEdit);
    db.SaveChanges();
}

Changing the Active field from false to true in countryToEdit produces the following SQL

update [dbo].[Countries]
set [Name] = @0, [ISOCode] = @1, [Active] = @2
where ([ID] = @3)
@0 nvarchar(256),@1 nvarchar(12),@2 bit,@3 int,@0='Algeria',@1='DZ',@2=1,@3=4

This is expected.

If I change the Active field from true to false in countryToEdit the following SQL is produced

update [dbo].[Countries]
set [Name] = @0, [ISOCode] = @1
where ([ID] = @2)
@0 nvarchar(256),@1 nvarchar(12),@2 int,@0='Afghanistann',@1='AF',@2=1

There is no attempt made to update the Active field.

like image 760
Cephas Avatar asked Feb 15 '10 06:02

Cephas


1 Answers

This ApplyCurrentValues in EF 4 question has the answer.

It should be

db.Countries.Attach(db.Countries.Single(c => c.ID == countryToEdit.ID));

If you attach a blank stub object the boolean fields are initialised to false. The ApplyCurrentValues call sees no change in the boolean value between the stub and the editied object.

The code above adds another DB query, but I can live with that.

like image 172
Cephas Avatar answered Nov 15 '22 11:11

Cephas