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

时间:2014-07-22 05:30:24

标签: c# asp.net web-services wcf

我正在创建一个从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; }     
    }      

3 个答案:

答案 0 :(得分:0)

此代码可以帮助您:对NorthwindDataContext怀疑 - 是列表还是数据头? 所以我有使用列表

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;

}

答案 1 :(得分:0)

使用lambda表达式:

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

答案 2 :(得分:0)

您的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(); } ,那么该方法应该看起来更像这样:

{{1}}