从DbContext执行存储过程

从DbContext执行存储过程

本文介绍了从DbContext执行存储过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SqlServer中有两个简单的存储过程:

I have two simple stored procedures in SqlServer:

  • SetData(@id int, @data varchar(10))
  • GetData(@id int).
  • SetData(@id int, @data varchar(10))
  • GetData(@id int).

GetData当前返回单行,单列结果集,但是如果需要,我可以将其更改为适当的函数.

GetData currently returns a single-row, single-column result set, but I could change it to be a proper function if needed.

DbContext实例执行这些操作的最佳方法是什么?

What would be the best way to execute these from a DbContext instance?

如果可能的话,我想避免做自己的连接状态管理和/或公开EF特定类型.我首先检索了ObjectContext并查看了Execute*函数,但是文档非常糟糕,并且缺少涉及存储过程的示例.

If possible, I'd like to avoid having to do my own connection state management and/or exposing EF-specific types. I started by retrieving the ObjectContext and looking at the Execute* functions, but the documentation is pretty bad and lacking examples involving stored procedures.

理想情况下,我希望能够做到这一点:

Ideally, I'd like to be able to do this:

myContext.ExecuteNonQuery("SetData", id, data);
var data = myContext.ExecuteScalar<string>("GetData", id);

推荐答案

DbContext提供了这些功能.使用:

DbContext offers these functions. Use:

IEumerable<...> result = myContext.Database.SqlQuery<...>(...)

执行检索存储过程和

int result = myContext.Database.ExecuteSqlCommand(...)

执行数据修改存储过程.

to execute data modification stored procedure.

这篇关于从DbContext执行存储过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 03:08