Are there any plans to better support using the State Pattern with TPH?

Topics: EF Runtime, General
Jan 4, 2013 at 9:43 PM

I have been trying to implement a State Pattern with TPH in EF5, but have determined that it isn't supported without hacking EF by using a custom sql statement to manually update the discrimantor column.  Are there any plans to make this scenario easier in EF6?  Perhaps by allowing the discrimantor column to be updated?

Developer
Jan 10, 2013 at 5:22 PM

HintonHQC,

When using TPH the value in the discriminator column is used when querying to determine the type of entity to create. Similarly, the type of entity is used to determine the discriminator value when sending updates to the database. Once an .NET object that represents the entity instance is created its type cannot be changed because .NET does not allow this. If EF allowed the discriminator to be changed then you would end up in a state where the type of object no longer matched the discriminator value. Furthermore, if you then queried for the object again EF would want to create an object of the new type, but then what should happen to the object that is already being tracked? Given these constraints on the way TPH mapping works it seems unlikely that we would allow the discriminator column to be modified through EF.

Thanks,
Arthur

 

Jan 10, 2013 at 6:10 PM

In trying to use EF TPH with the State Pattern we create a new .NET Object that represents the new state and essentially clone the object's values from the prior state (including and especially the primary key).  We then AttachAsModified the new object to the context and do a SaveChanges - that works in EF today except it doesn't include the new discriminator column value in the update statement (it doesn't include that column in the update at all).  

 

To your second question of what would you do when you do a query and now the types are different - I would imagine today that what happens is that when you query and the object has been modified by some other process you then update the values of the object being tracked - in the case where the type is different rather than update - you dump the old object and start tracking the new one (because it is now a different type).

Would it strengthen the case for consideration of doing something like this if it was upvoted on UserVoice?

Thanks,

Bryan

Developer
Jan 11, 2013 at 6:22 PM

I think it's unlikely that we would do anything that either implicitly or explicitly involves changing the runtime type of a .NET object. That being said, if somebody presented a really nice design that was a great user experience then we would obviously consider that. But given the constrains of the CLR/.NET and the way EF materialization and tracking works it seems unlikely that such a design exits.

Thanks,
Arthur