您的位置:首页 > 数据库

[代码]如何使用存储过程返回行集(LINQ to SQL)

2010-10-22 00:19 549 查看
简单的说,就是在对象模型中创建一个函数,让其映射到数据库中的存储过程。然后通过调用对象模型中的这个函数达到调用映射的那个存储过程的目的。
此演示代码首先给出了测试中用到的存储过程的定义,然后是映射函数的定义,同时也给出了结果类的代码。最后是调用函数并显示结果的代码。

存储过程的定义:
CREATE PROCEDURE [dbo].[CustomersByCity]
    (@City NVARCHAR(20))
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    SELECT CustomerID, ContactName, ContactTitle, City from Customers
        as c where c.City=@City
END

映射到存储过程的函数如下:
[Function(Name="dbo.CustomersByCity")]
public ISingleResult<CustomersByCityResult> CustomersByCity(
    [Parameter(Name="City", DbType="NVarChar(20)")] string city)
{
 IExecuteResult result = this.ExecuteMethodCall(this,
        ((MethodInfo)(MethodInfo.GetCurrentMethod())), city);
 return ((ISingleResult<CustomersByCityResult>)(result.ReturnValue));
}


结果类的定义如下,如果你注意观察的话,一定会发现结果类的列成员和存储过程中查询的数据列是相对应:
[DataContract()]
public partial class CustomersByCityResult
{
 
 private string _CustomerID;
 
 private string _ContactName;
 
 private string _ContactTitle;
 
 private string _City;
 
 public CustomersByCityResult()
 {
 }
 
 [Column(Storage="_CustomerID", DbType="NChar(5) NOT NULL", CanBeNull=false)]
 [DataMember(Order=1)]
 public string CustomerID
 {
  get
  {
   return this._CustomerID;
  }
  set
  {
   if ((this._CustomerID != value))
   {
    this._CustomerID = value;
   }
  }
 }
 
 [Column(Storage="_ContactName", DbType="NVarChar(30)")]
 [DataMember(Order=2)]
 public string ContactName
 {
  get
  {
   return this._ContactName;
  }
  set
  {
   if ((this._ContactName != value))
   {
    this._ContactName = value;
   }
  }
 }
 
 [Column(Storage="_ContactTitle", DbType="NVarChar(30)")]
 [DataMember(Order=3)]
 public string ContactTitle
 {
  get
  {
   return this._ContactTitle;
  }
  set
  {
   if ((this._ContactTitle != value))
   {
    this._ContactTitle = value;
   }
  }
 }
 
 [Column(Storage="_City", DbType="NVarChar(15)")]
 [DataMember(Order=4)]
 public string City
 {
  get
  {
   return this._City;
  }
  set
  {
   if ((this._City != value))
   {
    this._City = value;
   }
  }
 }
}

调用映射到存储过程的函数并显示查询结果:
NorthwindDataContext db = new NorthwindDataContext(@"C:/LINQ/Northwind.mdf");
ISingleResult<CustomersByCityResult> LondonCustomers =
    db.CustomersByCity("London");
foreach (var CustomerObject in LondonCustomers)
{
    Console.WriteLine("CustomerID = {0} City = {1}",
        CustomerObject.CustomerID,
        CustomerObject.City);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: