2

I have a standard C# MVC project which has a domain layer using EF and repository pattern. Say I have a model like:

public class MainModel 
{
    public int MainModelID {get; set;}
    //Many other properties
    public List<Organization> CompetingOrganizations {get;set;}
}

On submission I need to populate the list of CompetingOrganizations based on the current value of other properties in the MainModel and the properties in the of all the Organizations in my database.

Right now my controller just calls the MainModelRepository.Update(...) after the View Model is validated and mapped onto the Domain Model without populating this list. I could populate competing organizations by:

  • making a call to the (for example) List<Organization> CompetingOrgList = OrganizationRepository.GetCompetingOrgs(model) from the controller, add them to the MainModel and persist in the same way, or by;
  • creating a MainModelRepository.UpdateWithCompetingOrgs(model) call that directly accesses the Organizations DbSet from the context in the MainModelRepository to figure out which organizations should be added by default.

Both of these options feels wrong, but without a service layer I am not sure how else I should handle it, and which method is cleaner?

  • There are many approaches here, which depend on your layers. Are you using repositories with a unit of work, or does every repository have its own context? What's your stance on passing a parent wih children to the parent repository, which blindly passes the thing (with its children) to EF, which will create the parent and its children? (pro: shorter code + it solves your issue / con: it obfuscates the fact that the children will be created). The direct answer to your question is "wherever your business logic is", and it's not clear whether that's currently inside your repositories or not. – Flater Jun 1 '18 at 8:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.