11

My table Sections (SQL Server) has ID as a primary key (int, identity) and SortIndex column (int) for sorting purposes.

The database has a trigger which sets SortIndex := ID at each INSERT. Obviously I want to change the sorting index later, by swapping the values for two rows.

I access the data using Entity Framework, all with MVC3 web application.

The problem is, Entity Framework doesn't update the value of SortIndex after I insert a new object into the table. It also caches all the data, so the following call to get all objects from this table will also give wrong SortIndex value for this object.

I tried changing StoreGeneratedPattern for this column in EDMX. This seems to be great and elegant but doesn't solve the problem.

If I set to Identity, it causes EF to properly update the value, but it becomes read only (exception thrown when trying to change). Setting it to Computed is similar, but instead of exception being thrown the values are just not written to the DB.

I can recreate the EF object every time if I need to use it after inserting an object, just by doing:

DatabaseEntities db = new DatabaseEntities()

But it seems like ugly workaround for me.

What's a solution to this problem?

Obviously something, what doesn't require me to do some action after every insert (and take a risk that it's forgotten and unnoticed) is preferred.

2
  • Possible duplicate: stackoverflow.com/questions/5445243/… Mar 8, 2012 at 10:14
  • It's similar, but he seems to have a field which he doesn't need to write to. "Computed" should be fine for him. It just doesn't work because of some bug.
    – Arek
    Mar 8, 2012 at 12:51

4 Answers 4

16

In short StoreGeneratedPattern means: the value is handled by the store and your application will never modify it. In such case you will get store generated value automatically after you call SaveChanges.

If you don't use StoreGeneratedPattern you will not get value and you will have to force another query execution to refresh your entity. You can for example do:

objectContext.Refresh(RefreshMode.StoreWins, yourSection);

Generally situations where you need to update values in both database through triggers and application don't play very nicely with EF (and probably also other ORM tools).

3
  • Thanks for the Refresh code, it looks better than recreating EF object. Unfortunately I cannot vote up with my reputation.
    – Arek
    Mar 9, 2012 at 9:29
  • I know I can accept, but I'm testing some other possible solutions here, so not yet.
    – Arek
    Mar 9, 2012 at 11:41
  • I gave up and found this to be impossible, and I mark this answer as accepted. I'll also describe what other things I tried, but in a separate answer, as it seems impossible to make new lines in comments.
    – Arek
    Mar 9, 2012 at 14:43
4

I found the answer from 'Ladislav Mrnka' being exact and marked it as accepted. Here are other workarounds, which I found while trying to find some solution. However, the solution I was looking for is in general not possible.

One of possibilities is to set StoreGeneratedPattern = Computed to let EF know, this value is calculated. And then, make a Stored Procedure to actually change the value of SortIndex. Typically it would change values in two rows (swap them), to change the sorting order. This procedure along with a trigger at INSERT gives guarantee the data stays consistent in the DB. It's not possible to create new row without proper value set in SortIndex, it's not possible to make two objects have the same value (unless stored procedure has a bug) and it's not possible to manually break the value somehow, because it's not possible to edit through EF. Looks like a great solution.

It's easily possible to have stored procedures mapped to functions in EF.

The problem is, it's now fine to enter a new row and EF properly updates data in its cache, but the cache is not updated after calling the stored procedure. Still some manual updated or refresh function is needed. Otherwise the following call to get objects sorted by SortIndex will give wrong results.

Other than that, it's possible to set MergeOption = MergeOption.OverwriteChanges for several entities, which causes EF to update data from the DB somewhat better. With this being done, it's possible to reread the object after inserting it or calling stored procedure and it will get refreshed. However, reading a collection of objects with db.Section.OrderBy(o => o.SortIndex) will still return cached results with wrong sorting order.

If anyone is interested, it's possible to make MergeOption default to something else by adding EF partial class and then partial method OnContextCreated, like here:

public partial class DatabaseEntities
{
    partial void OnContextCreated()
    {
        Subsection.MergeOption = MergeOption.OverwriteChanges;
        Section.MergeOption = MergeOption.OverwriteChanges;
        Function.MergeOption = MergeOption.OverwriteChanges;
    }
}
0
0

Do you know if you'll work with that column again in the same request?

I would use the context per request scenario, which usually gets you out of many problem, because a new EF context is created with every request, so you have a fresh data once per request.

With long lived context, there can grow incosistencies as you described.

Anyways the StoreGeneratedPattern setted to computed should be right. But it updates itself only when you're storing the actual entity. It's not getting updated by inserting or updating any other entity.

from http://msdn.microsoft.com/en-us/library/dd296755(v=vs.90).aspx

If you create a new entity or change an existing entity, the values of properties with StoreGeneratedPattern set to Computed are retrieved from the server when you call the SaveChanges method in your application. If you assign a value to a property with StoreGeneratedPattern set to Computed in your application, the value will be overwritten with the server-generated value when you call the SaveChanges method.

We're using the computed value option for SQL sequenced GUID, and it's working OK.

4
  • What I'm doing is (1) add new object, (2) get and return all objects ordered by SortIndex to update the webpage. So yes, I'm using SortIndex again in the same request.
    – Arek
    Mar 8, 2012 at 10:43
  • And StoreGeneratedPattert = Computed - this seems to update the object properly, but I cannot modify the SortIndex anymore. I try, but after I do SaveChanges() old values are restored. It seems the EF just quietly ignores these changes.
    – Arek
    Mar 8, 2012 at 10:45
  • Yes, storeGenerated clearly says that it's generated in store, so it doesn't bother to write it. Maybe best for you will be to set the entity.SortIndex = entity.id just after the save, then you can work with it as you would like probably. Mar 8, 2012 at 12:42
  • This is a similar workaround as recreating the main EF object. It would work but if forgotten, you have a bug and possibly no idea about it. I wish there would be something more elegant.
    – Arek
    Mar 9, 2012 at 9:25
0

I had a similar situation with a Sql Server Quote table with a varchar QuoteNumber column that is a non-primary unique key whose value is generated by an after-insert trigger. The trigger is used because the generated value is derived by fetching data from a foreign key table. Sql Server schema identity declarations do not allow you to pull information from other tables.

I'd like EF to treat this varchar column like an identity and do nothing to it on update and reread it after insert. EF will do so if there is a .HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity) property to a non-identity column in the code it generates to configure the Entity like so (scroll right):

public QuoteConfiguration(string schema)
{
    ToTable("Quote", schema);
    HasKey(x => x.ID);

    Property(x => x.ID).HasColumnName(@"ID").HasColumnType("int").IsRequired().HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);
    Property(x => x.QuoteNumber).HasColumnName(@"Quote_Number").HasColumnType("varchar").IsOptional().IsUnicode(false).HasMaxLength(64).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);
}

My EF model is code first and generated by Simon Hughes' EntityFramework Reverse POCO Generator. At first, I could not figure out how to make the generator add this property to a column that is not declared as an identity in Sql Server.

Rereading the entire Quote entity after insert did not retrieve the auto-generated QuoteNumber. Then I discovered that re-reading just the QuoteNumber column after insert defeated the entity cache. But, I felt dirty doing it.

Finally, I worked with Simon Hughes to discover how to get his EF Reverse POCO to do it for me. You just extend the UpdateColumn function in your *.tt file like so:

Settings.UpdateColumn = (Column column, Table table) =>
{
        if (table.Name.Equals("Quote", StringComparison.InvariantCultureIgnoreCase)
            && column.Name.Equals("Quote_Number", StringComparison.InvariantCultureIgnoreCase))
        {
            column.IsStoreGenerated = true;
        }
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.