-1

I need a bit of advice. I am new to .NET MVC and I was wondering, where I'm supposed to store linq queries? In the instance below I have put them in my controller like so

public ActionResult Index()
    {
        var vehicles = from v in db.Vehicles
                       from m in db.Makes
                       from mods in db.Models
                       where v.Model.ModelID == mods.ModelID
                       where mods.Make.MakeID == m.MakeID
                       select v;

        return View(vehicles.ToList());
    }

Am I going about this the right way bearing in mind queries could get a lot more complex?

Mageking Que
  • 339
  • 1
  • 9
  • It is really your call. There are many discussion on this topic (i.e. http://stackoverflow.com/questions/4565681/where-does-the-business-logic-layer-fit-in-to-an-mvc-application?rq=1 matches my opinion, but http://stackoverflow.com/questions/18563229/mvc-where-to-put-business-logic suggest opposite. When searching for other answers make sure to understand that "ASP.Net MVC" does not use "MVC pattern", but rather "MVVM pattern". – Alexei Levenkov Nov 16 '14 at 21:50
  • Thanks Alexei, that's very helpful. I still have a lot to learn about design patterns. Do you have any suggestions of where I could go to get started? – Mageking Que Nov 16 '14 at 21:54

1 Answers1

2

What I would do in your situation is to use the Repository-pattern, and in this way avoid the dependency of LINQ in your controller. I've give you a sort of outline below.

Define a repository interface:

public interface IRepository
{
   public IEnumerable<Vehicle> FetchAllVehicles();
}

then create a implementation of this repository, using LINQ to do the actual work of fetching the Veihcles:

public class Repository : IRepository
{
   public IEnumerable<Vehicle> FetchAllVehicles()
   {
      var vehicles = from v in db.Vehicles
                       from m in db.Makes
                       from mods in db.Models
                       where v.Model.ModelID == mods.ModelID
                       where mods.Make.MakeID == m.MakeID
                       select v;

        return vehicles.ToList();
   }
}

then use the repository in your controller:

private IRepository _repo = new Repository();

public ActionResult Index()
{
   return View(_repo.FetchAllVehicles());
}
Håkan Fahlstedt
  • 2,040
  • 13
  • 17