0

I am creating a web application, is it possible to use LINQ queries in the Model ,instead of using it in the Controller?

Thanks

4
  • 2
    Do you mean at view? Because the model is a class you pass to it. It just keeps data not more. Nevertheless you are not restricted from using LINQ anywhere you want as it's just a set of extension methods. Commented May 31, 2012 at 8:34
  • Not at view, I want to use it in model class Commented May 31, 2012 at 8:36
  • you can use it in any class. But in my oppinion, using any manipulations on data inside of model class is a bad design decision almost in every case Commented May 31, 2012 at 8:38
  • @ILya: only if you are using anemic models. Nothing prevents you from encapsulating model-specific logic in the model. It's a class not a data storage unit. Commented May 31, 2012 at 9:10

2 Answers 2

2

I would recommend you to use your LINQ queries in repository class.

Then you use your Repository methods inside your controller.

Lets say I have a repository class by the name of "CreateRepository" and this is my Createcontroller:

 public class CreateController : Controller
    {
        CreateRepository CreateRepository = new CreateRepository();

        public ActionResult Index()
        {
            var ListOfAllUserNames = CreateRepository.GetAllUserNames();

            // etc etc 
            return View();
        }

And this is my CreateRepository Class:

public class CreateRepository
 {   

   public List<User> GetAllUserNames()
       {
          return db.User.OrderBy(f => f.Username).ToList();
       }
 }

This is a example on what I mentioned above.

Sign up to request clarification or add additional context in comments.

1 Comment

Your answer make more sense.
1

Yes you can use LINQ queries in the model.

Here is an example :

using System.Linq;
using System.Linq.Expressions;
.
.
.
public class PostRepository
{
    DataClassesDataContext db = new DataClassesDataContext();

    public IQueryable<Post> FindByParentId(int parentId)
    {
        return from post in db.Posts
               where post.ParentID == parentId
               select post;
    }

4 Comments

@user841852: LINQ queries are no different in a model than in any other code. Any example of a linq query will work in a model as well as in a controller or view or windows app or anything else...
And how repository is related to the model?
@ssx What is IPostRepository here?
@user841852 it's an interface, but you can just skip it for the example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.