当前位置: 首页 > 编程语言 > C#

如何使用EF执行带输入输出参数的存储过程?分享

时间:2023-04-10 23:41:53 C#

如何使用EF执行带输入输出参数的存储过程?我使用EF代码优先方法,我使用这样的迁移创建了存储过程:WITHRecursiveCTEAS(SELECTIdFROMdbo.PhysicalObjectsWHEREParentIdin(Select*from@IdsList)--WhereId=108UNIONALLSELECTt.IdFROMdbo.PhysicalObjectstINNERJOINRecursiveCTEcteONt.ParentId=cte.Id)复制代码选择*从递归CTE结束");}publicoverridevoidDown(){Sql(@"DropTypeIdsListGoDropProceduregetChildIds");现在,如果我转到sqlservermanagementstudio并执行以下脚本:Declare@Idsdbo.IdsListInsertinto@IdsSELECT1ExecgetChildIds@Ids它会成功执行,但现在我尝试按如下方式执行存储过程:varidsList=newSqlParameter{ParameterName="idsList",Value=newint[]{1,2,3,4,5}};varidParams=newSqlParameter("idParams",SqlDbType.Structured){Direction=System.Data.ParameterDirection.Output};var结果=dbContext.Database.SqlQuery("getChildIds@idsList,@idParamsout",idsList,idParams);varidsResult=(List)idParams.Value;它不返回任何内容,那么我如何使用Table类型的输入和输出参数执行存储过程?您必须以不同的方式获取数据:您不能在表值参数中返回数据。表值参数仅供输入;不支持OUTPUT关键字。我是这样解决的。首先,我更新了我的存储过程以返回ID,如下所示:AS(SELECTIdFROMdbo.PhysicalObjectsWHEREParentIdin(Select*from@IdsList)UNIONALLSELECTt.IdFROMdbo.PhysicalObjectstINNERJOINRecursiveCTEcteONt.ParentId=cte.Id)SELECTIdFromRecursiveCTE结束");}publicoverridevoidDown(){Sql(@"DropProceduregetChildIdsGoDropTypeIdsList");下面是我如何使用实体框架来执行存储过程:vardataTable=newDataTable();数据表。表名="idsList";dataTable.Columns.Add("Id",typeof(int));dataTable.Rows.Add(1);dataTable.Rows.Add(2);SqlParameteridsList=newSqlParameter("idsList",SqlDbType.Structured);idsList.TypeName=dataTable.TableName;idsList.Value=数据表;varresults=dbContext.Database.SqlQuery("execgetChildIds@idsList",idsList).ToList();我希望我的代码可以帮助其他人在SQL中遇到同样的问题使用用户程序/函数和内置函数的最佳解决方案是这个库-https://github.com/Dixin/EntityFramework.Functions实现起来非常简单它还允许遵循代码优先方法在您的情况下,您需要使用表值函数定义模型[ComplexType]publicclassIdModel{publicintId{get;放;}}在DbContextOnModelCreating(DbModelBuildermodelBuilder){modelBuilder.Conventions.Add(newFunctionConvention());中声明类型和约定保护覆盖无效modelBuilder.ComplexType();base.OnModelCreating(模型构建器);}在DbContext中定义函数[Function(FunctionType.TableValuedFunction,nameof(ufnGetChildIds),Schema="dbo")]publicIQueryableufnGetChildIds([Parameter(DbType="IdModel",Name="IdsList")]ListIdsList){=newObjectParameter("IdsList",IdsList);返回this.ObjectContext()。CreateQuery($[{nameof(this.ufnGetChildIds)}](@{nameof(IdsList)})",IdsListParameter);}并从你的DbContext中使用它以上是C#学习教程:HowtouseEFtoexecutewithinputandStoredprocedurewithoutputparameters?如果分享的内容对你有用,需要了解更多C#学习教程,希望你多多关注——[TestMethod]publicvoidCallTableValuedFunction(){using(DbContextdatabase=newDbContext()){IQueryable员工=数据库。ufnGetChildIds(newList{newIdModel{Id=1}});}}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: