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 m开发者_如何学JAVAy 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.
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.
To avoid two trips to the database (select, and update) you can modify the boolean values twice.
Example:
public void EditCountry(Country countryToEdit)
{
db.Countries.Attach(new Country
{
ID = countryToEdit.ID,
Active = !countryToEdit.Active
});
db.Countries.ApplyCurrentValues(countryToEdit);
db.SaveChanges();
}
Setting the default value of your boolean to the opposite of what it will be updated to will flag Entity Framework that the field has been updated.
I know this isn't the best looking code; and may cause confusion for another developer, but it will likely have the best performance because you don't have to hit the database twice.
精彩评论