将 DbContext.Database.SqlQuery<TElement>(sql,params) 与泛型类型一起使用

Using DbContext.Database.SqlQuery<TElement>(sql,params) with a generic type

提问人:Kevin M 提问时间:1/23/2023 更新时间:1/23/2023 访问量:76

问:

我发现自己一遍又一遍地为不同的存储过程使用一组非常相似的代码

SqlParameter[] parameters = {
  new SqlParameter("@somevar", 123),
  new SqlParameter("@othervar", 456)
}
List<MyClass> result;
using (MyContext contextName = new MyContext())
{
  result = contextName.Database.SqlQuery<MyClass>("mystoredproc @somevar, @othervar", parameters).ToList();
}

我心想,为什么不制作一组标准的代码来传入存储过程和 SqlParameter[]

MyClass result = getStoredProcResult(“mystoredproc”, 参数);

我苦苦挣扎的地方是使 SqlQuery 泛型。

我试过使用

result = contextName.Database.SqlQuery<object>(procname, parameters);

但是,我总是只拿出一个对象,它不会返回到 MyClass 我尝试使用类型,但出现错误。

我是否遗漏了什么,或者它只是不能处理一个通用类,而我注定要重复自己?

C# System.Data.SqlClient

评论

2赞 Alexander Petrov 1/24/2023
不要重新发明 Dapper。
0赞 Kevin M 1/24/2023
我从没想过使用 Dapper tbh。现在再看一看。谢谢
0赞 Kevin M 1/24/2023
好吧,当我应该使用 Dapper 时,我浪费了很多时间和精力。@AlexanderPetrov - 谢谢。如果你想把它作为答案,我很乐意这样标记它。
1赞 Mike 1/24/2023
这是 EF 8 更改列表中的。在 EF 7 中,必须定义一个实体才能执行此操作。

答: 暂无答案