请问在.net mvc3中使用EFcodeFirst数据库框架如何使用存储过程!
全副身家给了,求详细
public string GetCoupon(int type) { using (var db=new ProbabilityContext()) { var coupon = new SqlParameter("@coupon", SqlDbType.VarChar, 50); coupon.Direction = ParameterDirection.Output; var parm = new SqlParameter[] { new SqlParameter("@TYPE", type), coupon }; string sql = @"EXEC [dbo].[GetCouponNo] @TYPE,@coupon OUTPUT"; db.Database.ExecuteSqlCommand(sql, parm); return Convert.ToString(parm[1].Value); } }
用这种 context.Database.SqlQuery 方式行不
这种能处理out 值么?
@Sai.: 可以 context.Database.SqlQuery<TResult> , TResult 就是返回的结果
@Yu: 谢谢啊,但是我是说存储过程的 输出参数?
@Sai.:
ALTER PROCEDURE [dbo].[P_GetCategoryByID] @ID nvarchar(128),@Name varchar(64) output AS BEGIN SELECT @Name=Name FROM Categories WHERE CategoryId=@ID; select CategoryId,Name,Comment from Categories END ================================= SqlParameter[] parms = new SqlParameter[2]; SqlParameter id = new SqlParameter("ID", "11a44466-6d9c-4c7e-b9e4-5a1369061119"); id.SqlDbType=SqlDbType.NVarChar; id.Size = 128; parms[0] = id; var outParam = new SqlParameter(); outParam.ParameterName = "Name"; outParam.SqlDbType = SqlDbType.VarChar; outParam.Size = 64; outParam.Direction = ParameterDirection.Output; parms[1]=outParam; var result = db.Database.SqlQuery<Category>("P_GetCategoryByID @ID,@Name output", parms); string name = outParam.Value as string;
public class Category { public string CategoryId { get; set; } public string Name { get; set; } public string Comment { get; set; } } 我这测试没问题的,不知能否帮到
EF Code First似乎对存储过程的支持不是很好,执行存储过程,一般会通过将DbContext转换为ObjectContext,再调用他的ExecuteFunction重载方法,但这些重载只能返回查询结果(表格的那种多行记录),或者返回受影响的行数,ExecuteFunction重载方法中有一些可以传入参数,但参数是ObjectParameter,这个类型的参数不支持想SQLParameter的Direction那样的参数类型设置。所以我觉得要执行返回值的话只能通过dbContext.Database.Connection(DbConnection实例)来执行,或者将就是通过dbContext.Database.ExecuteCommand重载方法间接执行存储过程语句:
declare @result int;
exec @result=sp_procedure 参数
select @result as '存储过程返回值'