Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Yes, you can use Entity Framework 4 and LINQ on top, it generates the parametrized query and executes it, that's the option.</p> <p>Another option is (and I did several times) to create a base class/interface, let's say:</p> <pre><code>public interface IExecutable { void Execute(IConnection connection); } public interface IExecutable&lt;TResult&gt; : IExecutable { TResult Result { get; } } public abstract ActionBase&lt;TResult&gt; : IExecutable&lt;TResult&gt; { protected void AddParameter(....); protected IDataReader ExecuteAsReader(string query) { //create a DB Command, open transaction if needed, execute query, return a reader. } protected object ExecuteAsScalar(string query) { //.... } //the concrete implementation protected abstract TResult ExecuteInternal(); IExecutable.Execute(IConnection connection) { //keep the connection this.Result = ExecuteInternal(); } //another common logic: } </code></pre> <p>Then you can create your concrete actions:</p> <pre><code>public sealed class GetUsersAction : ActionBase&lt;&lt;IList&lt;User&gt;&gt; { //just a constructor, you provide it with all the information it neads //to be able to generate a correct SQL for this specific situation public GetUsersAction(int departmentId) { AddParameter("@depId", departmentId); } protected override IList&lt;User&gt; ExecuteInternal() { var command = GenerateYourSqlCommand(); using(var reader = ExecuteAsReader(command)) { while(reader.Read) { //create your users from reader } } //return users you have created } } </code></pre> <p>Very easy to create concrete actions!</p> <p>Then, to make it even easier, create an ExecutionManager whose concern is how to get the connection and execute the action:</p> <pre><code>public sealed ExecutionManager() { TResult Execute&lt;TResult&gt;(IExecutable&lt;TResult&gt; action) { var connection = OhOnlyIKnowHowTOGetTheConnectionAnfHereItIs(); action.Execute(connection); return action.Result; } } </code></pre> <p>Now just use it:</p> <pre><code>var getUsersAction = new GetUsersAction(salesDepartmentId); //it is not necessary to be a singletone, up to you var users = ExecutionManager.Instance.Execute(getUsersAction); //OR, if you think it is not up to ExecutionManager to know about the results: ExecutionManager.Instance.Execute(getUsersAction); var users = getUsersAction.Result </code></pre> <p>Using this simple technique it is really easy to move all the connection/command/execution logic away from the concrete actions into the base class, and the concrete actions' concerns are just generating SQLs and converting database output into some meaningful results.</p> <p>Good luck :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload