问题
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