概述:EFCore中使用存储过程。
一 存储过程-带参数(包括返回参数),并返回结果集
1.创建存储过程
create PROCEDURE pro_test
(
@Param01 int
,@Result01 int output
,@Result02 nvarchar(100) output
)
as
begin
select @Param01 as Col01,100 as Col02 --第一个结果集
set @Param01=999
declare @temp int
set @temp=@Result01
set @Result01=@Result02--第一个返回值
set @Result02=CAST(@temp as nvarchar(100))+'-12121212'--第二个返回值
select 100 as AA ,'fdfdasf' as BB--第二个结果集
end
2.创建存储结果的对象
- 创建存储过程返回的结果集对象
public class ProTestResultMobel
{
public int Col01 { get; set; }
public int Col02 { get; set; }
}
- 在DbContext中添加属性,用于存储返回结果集
public partial class TestContext : DbContext
{
//...
public virtual DbQuery<ProTestResultMobel> ProTestResultMobel { get; set; }
//...
}
1.执行并获取结果集与返回结果
- 通过TestContext调用存储过程,并接受结果集和返回结果
public void ProcHasParam()
{
var _context = new TestContext();
//返回结果1
var outoutParamter01 = new SqlParameter()
{
ParameterName = "Result01",
SqlDbType = SqlDbType.Int,
Direction = ParameterDirection.Output
};
//返回结果2
var outoutParamter02 = new SqlParameter()
{
ParameterName = "Result02",
SqlDbType = SqlDbType.NVarChar,
Size=100,
Direction = ParameterDirection.Output
};
var param01 = new SqlParameter("Param01", 1);
//顺序可以任意,内部是通过ParamName匹配的
var paramList = new SqlParameter[]
{
param01,
outoutParamter02,
outoutParamter01,
};
string querySql = "exec pro_test @Param01 ,@Result01 output,@Result02 output";
//即使存储过程返回了多个结果集 但是会自动匹配与属性匹配的那个结果集
var data = _context.ProTestResultMobel.FromSql(querySql, paramList).ToList();
//获取返回结果1
var result01 = outoutParamter01.Value as int? ?? default(int);
//获取返回结果2
var resutl02 = outoutParamter02.Value as string ?? string.Empty;
}