如何在从SQL Server数据库检索数据时使用WCF服务中的where子句进行查询

本文关键字:服务 WCF where 子句 查询 SQL Server 数据库 数据 检索 | 更新日期: 2023-09-27 18:14:08

我正在创建一个从SQL Server数据库访问数据的WCF服务。由于我是新手,所以我无法在查询中添加where子句。请告诉我如何检索某些特定参数的数据。把我的代码贴在

下面

IServices1.cs:

    [OperationContract]
    [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, 
               UriTemplate = "GetAllCustomers")]
    List<Consumer> GetAllCustomers();

Service.svc.cs:

 namespace JSONWebService
 {
    public class Service1 : IService1
    {
       public List<Consumer> GetAllCustomers()
       {
           NorthwindDataContext dc = new NorthwindDataContext();
           List<Consumer> results = new List<Consumer>();
           Consumer consumer = new Consumer();
           foreach (Output_Master cust in dc.Output_Masters)
           {
               results.Add(new Consumer()
               {
                   Record_ID = cust.Record_ID,
                   MeterCycle = cust.MeterCycle,
                   Agency = cust.Agency,
                   WorkDate = cust.WorkDate
               }
               return results;
           }
      }

Consumer.cs:

namespace JSONWebService
{
    [DataContract]
    public class Consumer
    {
       [DataMember]
       public string Record_ID { get; set; }
       [DataMember]
       public string MeterCycle { get; set; }
       [DataMember]
       public string Agency { get; set; }
       [DataMember]
       public decimal? WorkDate { get; set; }     
    }      

如何在从SQL Server数据库检索数据时使用WCF服务中的where子句进行查询

您的GetAllCustomers方法应该更像这样:

public List<Consumer> GetAllCustomers() {
   return
      new NorthwindDataContext()
      .Output_Masters
      .Where(consumer => consumer.SomeParameter == someValue)
      .ToList();
}

这里假定Output_MastersConsumer的集合。实际上,您可能需要引用CustomersConsumers属性,但这取决于NorthwindDataContext类的设计。

如果NorthwindDataContext实现了IDisposable,那么这个方法实际上应该看起来更像这样:

public List<Consumer> GetAllCustomers() {
   using (var northwind = new NorthwindDataContext())
      return
         northwind
         .Output_Masters
         .Where(consumer => consumer.SomeParameter == someValue)
         .ToList();
}

使用lambda表达式:

results = results.Where(i => i.YourColumnName == paramvalue).ToList();

这段代码可以帮助你:怀疑与NorthwindDataContext -是列表或数据阅读器?输入use list where

public List<Consumer> GetAllCustomers()
{
    NorthwindDataContext dc = new NorthwindDataContext();
    List<Consumer> results = new List<Consumer>();
    Consumer consumer = new Consumer();
    foreach (Output_Master cust in dc.Output_Masters)
    {
        results.Add(new Consumer()
        {
           Record_ID = cust.Record_ID,
 MeterCycle = cust.MeterCycle,
 Agency = cust.Agency,
 WorkDate =cust.WorkDate
     });
}
///examble
results = results.Where(i => i.Record_ID == "1").ToList(); 
return results;
}