Executing stored procedures from a DbContext

*爱你&永不变心* 提交于 2020-01-12 07:31:49

问题


I have two simple stored procedures in SqlServer:

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

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

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

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);

回答1:


DbContext offers these functions. Use:

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

to execute retrieval stored procedure and

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

to execute data modification stored procedure.



来源:https://stackoverflow.com/questions/6282447/executing-stored-procedures-from-a-dbcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!