3

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

ChadT
  • 7,598
  • 2
  • 40
  • 57
  • Could you show an example of how your updating a value, and submitting to the db – msarchet Aug 30 '12 at 00:13
  • Can you try adding this `databaseSession.ObjectStateManager.ChangeObjectState(myEntity, System.Data.EntityState.Modified);` – msarchet Aug 30 '12 at 00:29
  • @msarchet question updated again... – ChadT Aug 30 '12 at 00:38
  • 2
    http://stackoverflow.com/questions/5042327/entity-framework-storegeneratedpattern-computed-property-problem take a look at that – msarchet Aug 30 '12 at 00:47
  • The only way will be to customize EDMX file, set default value in EDMX and customize text template to set as default values in property definition inside class. I have done this. – Akash Kava Jul 29 '13 at 19:21

1 Answers1

1

It is my understanding that computed columns really aren't meant to be set manually.

If that works for you, you may simply set the properties to their default values in the default constructor of the entity; it's what it's there for, and you have the extra advantage that you will see those values even before the call to SaveChanges.

Update: Relevant suggestion.

tne
  • 7,071
  • 2
  • 45
  • 68