Search code examples
.netentity-frameworkblazorcoding-stylecode-maintainability

How to manage multiple uses of a model in an application?


I'm currently implementing an application and have for example a Customer model that's used in several different parts of the application. Each part only uses a subset of the properties from the Customer model. For instance:

  • In one place, I use two properties.
  • In another place, I use ten properties.
  • In yet another place, I use three properties.

I'm unsure whether I should create a different Customer model for each use case or stick with one big Customer model containing all properties.

Creating different models for each scenario seems like it would lead to redundancy and be difficult to maintain, especially when adding new properties. However, using a single large model everywhere might be inefficient and expose unnecessary data.

What are the best practices for managing this in an application? Should I use multiple models or another approach? Any suggestions or examples would be greatly appreciated.

What approach would you recommend to keep the code clean, maintainable, and efficient?

Thank you in advance for your help!


Solution

  • EF supports projection specifically for this. (via Select or methods in various mapping libraries such as Automapper's ProjectTo<T>)

    My general advice is to have entities solely concerned with the data domain. The representation of the data. For the various consumers of that data, create view models or DTOs to be concerned solely with the servicing those needs. Projection should be the default for all Read-type operations, where view models or DTOs are the transport between services/controllers and the end consumer. Entities are loaded/used solely for manipulation. (Update / Insert) EF supports working with detached entities but this is honestly responsible for systems becoming rabbit holes for problems and result in less efficient database operations.

    For very large systems you can also employ bounded DbContexts which are essentially just DbContexts specialized for certain functionality where you can nominate one as the owner responsible for a given entity while others that share references to that table can use simplified read-only entity definitions themselves.

    A good example of a bounded scenario is Authentication/Authorization. If you are using ASP.Net Core's authentication with it's Users and Roles etc. you can have an AuthenticationDbContext extending .Net Core's AuthenticationDbContext and managing auth challenges, managing users etc. for admin-level functionality. For main application classes you might want to reference Users as well for things like CreatedBy/LastModifiedBy etc. but you don't need, nor risk exposing details like roles and permissions etc. so the main application DbContext can have it's own summarized User class that just provides info the application might need to display/use. (UserId, Name, Email, etc.)