如何在从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; }
}
您的GetAllCustomers
方法应该更像这样:
public List<Consumer> GetAllCustomers() {
return
new NorthwindDataContext()
.Output_Masters
.Where(consumer => consumer.SomeParameter == someValue)
.ToList();
}
这里假定Output_Masters
是Consumer
的集合。实际上,您可能需要引用Customers
或Consumers
属性,但这取决于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;
}