views:

414

answers:

1

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.

What am I doing wrong?

+4  A: 

This http://stackoverflow.com/questions/2272325/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.

Cephas
@Cephas you can still use the stub entity approach if you are able to change your properties to nullable bools. The default value will then be null and ApplyCurrentValues will pick up the modification from null on the stub to false on the current entity and emit the extra sql for the update.
Simon Fox