Entity Framework Code First TPH Inheritance - Can Different Child Classes Share a Field?

I have an Entity structure model created using the Entity Framework Code First that uses table inheritance into a hierarchy where the structure looks something like this:

public abstract class BaseState { public int Id { get; set; } public string StateName { get; set; } // etcetera } public class CreatedState : BaseState { public User Owner { get; set; } } public class UpdatedState : BaseState { public User Owner { get; set; } } 

Now, what is being created in my BaseStates table, I saved Owner_Id and Owner_Id1 . But given that no class will ever be both CreatedState and UpdatedState , it would seem logical to use one Owner_Id for both. Which will also facilitate database tracking.

My main question is: is this possible with Code First EF4?

I tried to display the columns:

 public class CreatedState : BaseState { [Column("OwnerId")] public User Owner { get; set; } } public class UpdatedState : BaseState { [Column("OwnerId")] public User Owner { get; set; } } 

It turned out to be ineffective.

Then I tried to create a generic parent class, which is probably more correct OO:

 public abstract class OwnedState : BaseState { public User Owner { get; set; } } public class CreatedState : OwnedState { } public class UpdatedState : OwnedState { } 

Again, no dice. Or, more worryingly, this works in some cases, and not in others (obviously, my real configuration is a bit more complicated) when I don't see exactly any difference between the classes in which it works.

Edit for more details on what fails: I have two fields that behave as I described above, we could name the related classes OwnedState and ActivityState , both of which I created as an abstract class, as shown in my last example. OwnedState has two classes that flow from it, ActivityState has three. There is ActivityState_Id in the database, but also OwnedState_Id and OwnedState_Id1 .

I do not see the differences between the OwnedState and ActivityState classes, except that they reference (both other objects), and yet in the database it seems that EF somehow interprets them differently - I do not understand. Understand that the internal device EF knows quite well how it makes this decision.

+4
source share
1 answer

If you want to have one Owner_ID identifier that both created and updated states should refer to, then the user user must be placed in BaseState.

I do not know what you are trying to do with this, but logically, you would not have the CreateState and UpdateState classes as classes, but more values โ€‹โ€‹of the State property (or a column in the database) to save the state (Created or updated). But, again, perhaps you are trying to do something else with this. I think so.

0
source

All Articles