I'm using EF (v5) against an existing database that has a large number of nullable fields with default values.
When inserting a new entity, if no value has been specified for a nullable field, null will be inserted (the database default will not be used). That makes sense in that EF can't determine if I really intended null or not.
If I set the fields to be StoreGeneratedPattern = Computed
however, it will use the default value on insert, however it will only ever use the default value. If I supply my own value (even on Update
), the value seems be ignored.
Is there a way for this scenario to work without making changes to the underlying database?
Example of the process I'm following:
var myEntity = databaseSession.MyEntities.Single(x => x.EntityID = 123);
myEntity.SomeField = 1;
databaseSession.SaveChanges();
SomeField
in this case is of type int?
and is set to StoreGeneratedPattern = Computed
Using EFProf, I can see the SQL query being issued is:
update [dbo].[MyEntities]
set @p = 0
where ([EntityID] = 123 /* @0 */)
Adding:
databaseSession.ObjectStateManager.ChangeObjectState(myEntity, System.Data.EntityState.Modified);
Causes an update statement to be generated that updates all fields in the table but crucially, it does not include any fields that are set to StoreGeneratedPattern = Computed