0

In some MVC frameworks I've used the Model has the method and SQL in the Model so that if you call the controller, it invokes a method on the model class (say Products), and it returns the data. In ASP.NET MVC Core, from what I have seen so far, there is a separate file besides the model to do the logic. Do I use two classes? They appear (the ones I read) to be using the Repository Pattern.

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public int Quantity { get; set; }
    public double Price { get; set; }
}

That's one class. Where do the methods to get the data go? Is the Repository Pattern necessary or it is a "Best Practice"?

public interface IStoreRepository
{
    //CRUD signatures
}

public ProductRepository : IStoreRepository
{

    //CRUD implementation
}
....

public IActionResult Products()
{
//A controller
//Call method in ProductRepository.GetAll or the like
}

If it matters I am attempting to use Dapper, not EF.

1

ASP.NET MVC doesn't have much to say about what you're asking. Everything you described is part of the Model; the design of the Model is entirely up to you.

However, you can get some rudimentary guidance from the ASP.NET site. If you dig in there, you will find code that looks like this:

public class MoviesController : Controller
{
    private readonly ApplicationDbContext _context;

    public MoviesController(ApplicationDbContext context)
    {
        _context = context;
    }

    // GET: Movies
    public async Task<IActionResult> Index()
    {
        return View(await _context.Movie.ToListAsync());
    }
}

Which is about as straightforward as it gets. As you can see, the data for the returned View is being drawn directly from an Entity Framework DBContext object.

In larger applications, you're probably going to want a more structured approach to your Model. Something like this:

DATABASE <=> Entity Framework <=> Service Layer <=> Controller <=> ViewModel <=> View

Where the Service Layer exposes business domain-specific methods, rather than CRUD. But again, none of this really has much to do with ASP.NET MVC proper.

Your Answer

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

Not the answer you're looking for?Browse other questions tagged or ask your own question.