温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Linq结果集形状怎么实现

发布时间:2021-12-01 15:46:56 来源:亿速云 阅读:85 作者:iii 栏目:编程语言

这篇文章主要介绍“Linq结果集形状怎么实现”,在日常操作中,相信很多人在Linq结果集形状怎么实现问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Linq结果集形状怎么实现”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

当存储过程可以返回多个Linq结果集形状时,返回类型无法强类型化为单个投影形状。尽管 LINQ to SQL 可以生成所有可能的投影类型,但它无法获知将以何种顺序返回它们。 ResultTypeAttribute 属性适用于返回多个结果类型的存储过程,用以指定该过程可以返回的类型的集合。

在下面的 SQL 代码示例中,Linq结果集形状取决于输入(param1 = 1或param1 = 2)。我们不知道先返回哪个投影。

ALTER PROCEDURE [dbo].[SingleRowset_MultiShape]  -- Add the parameters for the stored procedure here  (@param1 int )  AS  BEGIN  -- SET NOCOUNT ON added to prevent extra result sets from  -- interfering with SELECT statements.  SET NOCOUNT ON;  if(@param1 = 1)  SELECT * from Customers as c where c.Region = 'WA' else if (@param1 = 2)  SELECT CustomerID, ContactName, CompanyName from   Customers as c where c.Region = 'WA' END

拖到O/R设计器内,它自动生成了以下代码段:

[Function(Name="dbo.[Whole Or Partial Customers Set]")]  public ISingleResult<Whole_Or_Partial_Customers_SetResult>   Whole_Or_Partial_Customers_Set([Parameter(DbType="Int")]   System.Nullable<int> param1)  {  IExecuteResult result = this.ExecuteMethodCall(this,   ((MethodInfo)(MethodInfo.GetCurrentMethod())), param1);  return ((ISingleResult<Whole_Or_Partial_Customers_SetResult>)  (result.ReturnValue));  }

但是,VS2008会把多结果集存储过程识别为单结果集的存储过程,默认生成的代码我们要手动修改一下,要求返回多个结果集,像这样:

[Function(Name="dbo.[Whole Or Partial Customers Set]")]  [ResultType(typeof(WholeCustomersSetResult))]  [ResultType(typeof(PartialCustomersSetResult))]  public IMultipleResults Whole_Or_Partial_Customers_Set([Parameter  (DbType="Int")] System.Nullable<int> param1)  {  IExecuteResult result = this.ExecuteMethodCall(this,   ((MethodInfo)(MethodInfo.GetCurrentMethod())), param1);  return ((IMultipleResults)(result.ReturnValue));  }

我们分别定义了两个分部类,用于指定返回的类型。这样就可以使用了,下面代码直接调用,分别返回各自的结果集合。

//返回全部Customer结果集  IMultipleResults result = db.Whole_Or_Partial_Customers_Set(1);  IEnumerable<WholeCustomersSetResult> shape1 =  result.GetResult<WholeCustomersSetResult>();  foreach (WholeCustomersSetResult compName in shape1)  {  Console.WriteLine(compName.CompanyName);  }  //返回部分Customer结果集  result = db.Whole_Or_Partial_Customers_Set(2);  IEnumerable<PartialCustomersSetResult> shape2 =  result.GetResult<PartialCustomersSetResult>();  foreach (PartialCustomersSetResult con in shape2)  {  Console.WriteLine(con.ContactName);  }

语句描述:这个实例使用存储过程返回“WA”地区中的一组客户。返回的Linq结果集形状取决于传入的参数。如果参数等于 1,则返回所有客户属性。如果参数等于2,则返回ContactName属性。

到此,关于“Linq结果集形状怎么实现”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI