MVC, I get it, but separating out the model for repository functions and maybe even business logic... Best practice?

StackOverflow https://stackoverflow.com/questions/17699997

Question

C# ASP .NET MVC 4.0

I understand the MVC pattern, but when it comes down to the model:

public class User
{
    int id { get; set }
    int name { get; set; }
}

I could see a benefit to dividing the business logic from the repository ( data fetchers ). Something like:

public class UserRepository
{
    IEnumerableList<User> GetAllUsers()
    {
        IEnumerableList<Product> users = //LINQ or entity;
        return IEnumerableList<Product> users;  
    }  

    int GetScoreByUserId( id )          
    {
        int score = //LINQ or entity;
        return score;  
    }  
}

Would the business logic go into the User class like:

public class User
{
    public int id { get; set }
    public int name { get; set; }

    public bool HasDiscount( int id )
    {
        if( GetScoreByUserId( id ) > 5 )
            return true;
        return false;
    }
}

Does anyone have a decent example. It's not as easy as 1 2 3 to find such an explicit example for me.

Does the above code seem okay? Should the Repository extend the User or should it be a separate class.. or should all of this stuff just go in the User class itself?

EDIT::---- So something like this?

public class UserBusinessLogic
{
    public bool HasDiscount( int id )
    {
        if( GetScoreByUserId( id ) > 5 )
            return true;
    }
}

EDIT::---- Clarification of how I understand this now

enter image description here

Was it helpful?

Solution

There are a few options in your situation. They are described in, for example, such book as "Patterns of Enterprise Application Architecture" by Martin Fowler. So it depends on the architecture pattern that you are going to choose.

When you were trying to find a solution you actually make smth like domain model pattern (User class for related business logic and separate UserRepository class for data access).

You can also merge these responsibilities in one class User (both business logic and data access) and so you will come to Active Record pattern.

However each pattern has its own pros and cons, I think that it definitely would be better to use domain model as it leads to OOP and right separation of concerns.

OTHER TIPS

I've had great success following this pattern: FooController -> FooTasks -> FooRepository.

It was shown to me by this smart guy.

"The controller gives the model to FooTasks, which in turn translates the model into a business object that goes to the FooRepository. The upside there is that any sort of lower-level representation of the data is nicely hidden from the controller. The controller shouldn't need to know how the data looks when it's getting persisted."

It helped me immensely with my MVC-applications.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top