问题
I have an Entity Framework Model created using Entity Framework Code First that is using Table Per Hierarchy inheritance where the structure looks a little 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 that creates is in my BaseStates
table I have Owner_Id
and Owner_Id1
stored. But given that no class will ever be both a CreatedState
and an UpdatedState
it seems as though it would be logical to use a single Owner_Id
for both. Which would also make it easier to follow the database.
My basic question is: Is this possible with Code First EF4?
I have tried to map the columns:
public class CreatedState : BaseState
{
[Column("OwnerId")]
public User Owner { get; set; }
}
public class UpdatedState : BaseState
{
[Column("OwnerId")]
public User Owner { get; set; }
}
That appeared to have no effect.
Then I tried creating a shared parent class, which is probably more correct OO anyway:
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 appears to work in some cases and not in others ( obviously my real configuration is slightly more complex ) when I can see precisely no difference between the classes where it does work.
Edit for more detail on what fails:
I have two fields that behave in the way I have described above, we might call the associated classes OwnedState
and ActivityState
, both of which I have created as an abstract class in the way shown in my last example. OwnedState
has two classes that derive from it, ActivityState
has three. In the database I have ActivityState_Id
but also OwnedState_Id
and OwnedState_Id1
.
I can see no difference at all between the OwnedState
and ActivityState
classes aside from the type that they reference ( both other entities ) and yet in the database it appears as though EF has somehow interpreted them differently- I don't understand the EF internals well enough to know how it makes that decision.
回答1:
If you want to have one Owner_ID to have both CreatedState and UpdatedState to refer to, then the User Owner should be placed in the BaseState.
I don't know what you are trying to do with this, but logically, you wouldn't be having CreatedState and UpdatedState as classes, but more of values of State property (or column in database) to save the state (Created or Updated). But, again, maybe you are trying something else with this.. I guess.
来源:https://stackoverflow.com/questions/16103518/entity-framework-code-first-tph-inheritance-can-different-child-classes-share