2

I want a method where I can call, that would query the database for my given query string. Which can be refferenced from different controllers/actions. (note, complexity of actual query is quite big).

So a few questions:

  1. Where would the code go. A new controller? Helper?
  2. How would I reference it (call it)?
  3. What object, if following my current style, would be the return type.

    public Something WebCostCentres()
    {
        using (var db = Database.OpenConnectionString(Mynamespace.Properties.Settings.Default.dbConnString, 
                               "System.Data.SqlClient"))
        {
            //ViewBag.CostCentres = db.Query("SELECT DISTINCT CostCentreNo");
            return db.Query("SELECT DISTINCT CostCentreNo");
        }
    }
    
2
  • What is your Database here - is that entlib? Commented Dec 12, 2011 at 9:52
  • Webmatrix.Data Sorry for slow reply, my internet cut off for half an hour. Reading through the answers provided. :) Commented Dec 12, 2011 at 10:25

3 Answers 3

2
  1. I would create some kind of Service class for this.
  2. You crate the service and call the method.
  3. The same type as your Query method. IEnumerable<Something> would be an option. You might have to call ToList or ToArray to execute the query, because the connection might be closed.

The service layer is often called repository. Google for this and you will find tons of examples.

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

1 Comment

re 3: As long as Query returns a completed list, not an active IEnumerable<T> - since the connection will be closed before it is consumed; might need a ToList()
2

1.Where would the code go. A new controller? Helper?

A class. Service oriented architecure wise.

2.How would I reference it (call it)?

As local variable in the page, filled via your trusted IOC container.

3.What object, if following my current style, would be the return type

None. Our current style is outdated. Ever heard of LINQ? The IQueryable extensions to .NET? It is not like they are new. It should return either IEnumerable or IQueryable, and be in general generic. Or a specific type in case only one number is returned.

Comments

2

repository pattern is applicable too

See an example http://mstecharchitect.blogspot.com/2009/08/aspnet-mvc-and-linq-to-sql-using.html

Comments

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.