Storing objects with Code First that are related as classes and subclasses

纵饮孤独 提交于 2019-12-24 19:07:21

问题


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 else has bumped into the same thing. Can it be done without resorting to manually applying the constraints in the database.


回答1:


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;}
}


来源:https://stackoverflow.com/questions/5989674/storing-objects-with-code-first-that-are-related-as-classes-and-subclasses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!