Entity Framework Code First POCOs and reasons why / why not setup relationships?
I wasn’t sure how to really word my question and I may change it based on some feedback.
When it is a good idea to have reference relationships (in my POCOs) setup so I can look up a parent record from a child or the reverse? Is it good practice to always have a way to “reverse” lookup an item or collection of items? I know it greatly depends on my application, but I just want to make sure of this before I start molding my application. So, let’s say I have two tables: States and Countries. States has a relationship with countries (many-to-one) and vice-versa (one-to- many). My class for state would have a property for Country and my Country class would a property for a collectio开发者_JS百科n of states. This is pretty standard.
In that example it may make sense to allow a country to lookup the associated states. Can someone think of a time where I may not care about that association so I don’t have the overhead of loading the items for a collection or a single item?
It is more about design decission of your entities. If you are using code first you always need a navigation property on at least one side to create relation in the database. You can start with a simple approach and define property on a side where it make sense and add it to other side only if you need it somewhere.
There are situations where you know that you will never work with child entity without its parent (it leads to theory about aggregation roots whre child entity can't exist without its parent). In such case child doesn't need to have navigation property to parent.
In your scenario do you expect to work with State
without Country
which it belongs to? If yes it is probable that you would like to know which States
a Country
contains but in the same time you would probably would like to know which Country
a State
belongs to so defining navigation property on both sides make sense.
精彩评论