Storing objects with Code First that are related as classes and subclasses
As an example I have an object Person, and Person is inherited by Man and Woman. Person contains the properties that both Man and Woman share, and Man and Woman contain the specific properties.
What I wanna do is store those in a database using Entity Framework 4.1 Code First. So I made three model objects
class Person {
int Id { get; set; }
string Name { get; set; }
string Weight { get; set; }
public virtual Woman Woman { get; set; }
public int WomanID { get; set; }
public virtual Man Man { get; set; }
public int ManID { get; set; }
}
class Woman {
int Id { get; set; }
bool IsPregnant { get; set; }
}
class Man {
int Id { get; set; }
bool ThinksWithDick { get; set; }
}
So I Person -> Man/Woman have a 1 to 0..1 relationship. And I don't know how to enforce this with Code First. I've read about 1 to 1 relations (here), but that's not what I'm looking for.
Maybe this is completely the wrong approach, but I'm sure someone els开发者_如何转开发e has bumped into the same thing. Can it be done without resorting to manually applying the constraints in the database.
Remove ManId and WomanId and Man and Woman from Person. Add a PersonId and Person to Woman and Man classes.
class Person {
int Id { get; set; }
string Name { get; set; }
string Weight { get; set; }
}
class Woman {
int Id { get; set; }
bool IsPregnant { get; set; }
int PersonId {get; set;}
public virtual Person {get; set;}
}
class Man {
int Id { get; set; }
bool ThinksWithDick { get; set; }
int PersonId {get; set;}
public virtual Person {get; set;}
}
精彩评论