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

5
  • Could you show an example of how your updating a value, and submitting to the db Commented Aug 30, 2012 at 0:13
  • Can you try adding this databaseSession.ObjectStateManager.ChangeObjectState(myEntity, System.Data.EntityState.Modified); Commented Aug 30, 2012 at 0:29
  • @msarchet question updated again... Commented Aug 30, 2012 at 0:38
  • 2
    stackoverflow.com/questions/5042327/… take a look at that Commented Aug 30, 2012 at 0: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. Commented Jul 29, 2013 at 19:21

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.