LINQ for Stored procedure returning Multiple ResultSets When you have SP which is returning multiple recordset and when you try to drag into dbml file then Visual Studio will not able to generate the code for this in the DataContext class. For this you have to manually write the code into Partial class (present with the dbml file), I usually drag my SP into dbml file and then copy past generated code into partial class and modify, just replace "ISingleResult" with "IMultipleResults". Let say you have one SP called "GerResources" which is returning two RecordSets Stored Procedure CREATE PROCEDURE [dbo].[GetResource] ( @ResourceID int ) AS Begin Select Id, Value from Employee where ResourceId = @ResourceID Select Name , Value from Content where ResourceId = @ResourceID End NameSpace using System.Data.Linq; using System.Data.Linq.Mapping; using System.Linq; using System.Linq.Expressions; DataContext Code public partial class YourDataContext : System.Data.Linq.DataContext { [FunctionAttribute(Name = "dbo.GetResource")] [ResultType(typeof(Employee))] [ResultType(typeof(Content))] public IMultipleResults GetResource(int resourceID) { IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), resourceID); return ((IMultipleResults)(result.ReturnValue)); } } Content and Employee is Entity class. public sealed class Employee { private int _id; private string _value; { get { return _id; } private set { _id = value; } } { get { return _value; } private set { _value = value; } } } public sealed class Content { private int _name; private string _value; { get { return _name; } private set { _name = value; } } { get { return _value; } private set { _value = value; } } } Call DataContext Method // Create and open the connection YourDataContext rdc = new YourDataContext(); List<Employee> emp = result.GetResult<Employee>().ToList(); List<Content> cont = result.GetResult<Content>().ToList(); foreach (Employee e in emp) { MessageBox.Show(e.Id + e.Value); } foreach (Content c in cont) { MessageBox.Show(c.Name + c.Value); } Note: If you have single Row returning from SP then use "Single()" method instead of "foreach" loop //Create and open the connection YourDataContext rdc = new YourDataContext(); List<Employee> emp = result.GetResult<Employee>().Single(); //Display the value MessageBox.Show(e.Id + e.Value); |
Friday, October 01, 2010
LINQ for Stored procedure returning Multiple ResultSets
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment