我想创建一个复杂类型以在实体管理器中使用动态构造的查询并使用 exec()
执行。是否可以?;由于我正在编写一个过滤器,如果不可能,您会怎么做?
此外,我正在使用 linq 进行评估,但过滤器需要很多表及其寄存器,因此效率是一个问题。
谢谢...
最佳答案
是的,您可以在上面使用 Entity Framework 4 和 LINQ,它会生成参数化查询并执行它,这是选项。
另一种选择是(我做了几次)创建一个基类/接口(interface),比方说:
public interface IExecutable
{
void Execute(IConnection connection);
}
public interface IExecutable<TResult> : IExecutable
{
TResult Result { get; }
}
public abstract ActionBase<TResult> : IExecutable<TResult>
{
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:
}
然后您可以创建您的具体操作:
public sealed class GetUsersAction : ActionBase<<IList<User>>
{
//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<User> ExecuteInternal() {
var command = GenerateYourSqlCommand();
using(var reader = ExecuteAsReader(command)) {
while(reader.Read) {
//create your users from reader
}
}
//return users you have created
}
}
非常容易创建具体的 Action !
然后,为了让它更容易,创建一个 ExecutionManager,它关注如何获得连接并执行操作:
public sealed ExecutionManager() {
TResult Execute<TResult>(IExecutable<TResult> action) {
var connection = OhOnlyIKnowHowTOGetTheConnectionAnfHereItIs();
action.Execute(connection);
return action.Result;
}
}
现在就用它吧
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
使用这种简单的技术,可以很容易地将所有连接/命令/执行逻辑从具体操作转移到基类中,而具体操作所关心的只是生成 SQL 并将数据库输出转换为一些有意义的结果。
祝你好运:)
关于c# - 如何从使用 exec() 的存储过程创建复杂类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3728148/