Search code examples
c#entity-frameworkentity-relationship

Repository with many methods or Entities with foreign keys


I have a database with a Customer, Supplier, and Services (this is a gross simplification, I really have about 100 tables)

I am developing a new Entity Framework library for accessing these tables.

A Customer has many Suppliers

A Supplier has many Services

I am trying to decide which approach to follow -

A ) Use mapping to connect the Customer to the Supplier and the Supplier to the Services, then every time I load a customer I get all his suppliers and their services (and other tables loaded)

B ) Have no mapping between entities, but provide methods in the relevant repository; e.g. in the supplier repository I'll have IEnumerable<Supplier> GetSupplierByCustomerID(int customerID)

EDIT Changed above to IEnumerable based on suggestions.

Are these the two main approaches when using EF? Which is considered better, from your perspective.

Is there another approach I'm not considering?


Solution

  • In general I feel like putting a repository over EF is always a good idea. You get to abstract your database logic from your client-side logic (or even business logic). And the specific case that you're mentioning you would be able to do one other nice benefit: You would only get the information that you want when you specifically call for it (like the GetSupplierByCustomerID example that you mentioned.

    Another approach you might consider is the one that I mentioned in the answer to this question: Bounded Contexts. The more separation of concerns that you have in your application, the better it will be in the long run for you and your fellow programmers (especially when you want to unit test it all).