linq - 从 .NET 客户端使用 ADO.NET 数据服务的服务操作

标签 linq linq-to-entities wcf-data-services service-operations

我正在尝试构建一个包含大量实体和一些服务操作的 ADO.NET 数据服务。一方面,我创建了一个 ASP.NET Web 应用程序,其中包含一个 ADO.NET 实体数据模型和一个 ADO.NET 数据服务。另一方面,我创建了第二个 ASP.NET Web 应用程序,它具有对数据服务的服务引用。

实体通过得很好,我可以使用 LINQ 来检索我想要的数据:

TestEntities entities = new TestEntities(
            new Uri("http://localhost/service/service.svc"));

var query = from customer in entities.Customers
                    where customer.ID == 1234
                    select customer;

query.ToList();

这有效。但是,我完全无法通过服务操作检索信息。
数据服务端代码:
public static void InitializeService(IDataServiceConfiguration config) {
    config.SetEntitySetAccessRule("*", EntitySetRights.All);
    config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
}

[WebInvoke]
public IQueryable<Customer> GetSomeCustomers() {
    TestEntities entities = new TestEntities();
    return from customer in entities.Customers
        where customer.ID > 0 && customer.ID < 20
        select customer;
}

当我将服务引用添加到我的客户端项目时,Visual Studio 没有选择任何服务操作。我知道我可以通过构造的 URI 和 DataServiceContext 对象或 TestEntities 对象(在本例中)或类似的东西的 BeginExecute 方法访问它们,但这不是我想要的。

我想要的是使用LINQ来遍历Service Operation返回的数据。
这可能吗?应该是吧?

最佳答案

简单的东西,一旦你知道。

只需了解几件事:

当前 DataServiceClientGenerator(使用 EntityClassGenerator)没有为服务操作创建方法。

服务操作不支持在上下文上使用 CreateQuery 方法,目前它们可以工作,因为客户端没有对此进行验证(您会注意到,如果您使用 CreateQuery,“()”被添加到查询方法的末尾像这样的“http://localhost/service.svc/method()?parameter=2”,你可以使用 CreateQuery 但不推荐。

并非所有服务操作都返回值,但对于本示例,我将仅展示返回值的示例。

public partial class NorthwindEntities
{ 
    public IQueryable<Order> OrdersByRegion(int regionId)
    {
     return this.Execute<Orders>(new Uri(string.Format("{0}OrdersByCountry?regionId={1}", this.BaseUri, regionId), UriKind.RelativeOrAbsolute));
    }
}

如果您需要更多信息,请随时提出任何问题。

PS。:在您的示例中,您不需要在服务操作(服务器端)上创建新的数据上下文,DataService 在调用服务时已经实例化了一个引用。

您实际上可以像这样在服务端覆盖数据上下文的创建:
protected override NorthwindEntities CreateDataSource()
{
     return new NorthwindEntities();
}

关于linq - 从 .NET 客户端使用 ADO.NET 数据服务的服务操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1559302/

相关文章:

c# - 从 LINQ 查询结果集中填充 DataSet 或 DataTable

c# - 不允许新事务,因为 session 中还有其他线程在运行 LINQ To Entity

c# - 我怎样才能让 OData DELETE 工作?

c# - LINQ:使用 AND 序列构建动态过滤器

c# - Linq查询获得唯一性和排序

c# - 给定开始日期和结束日期的简单方法

.net - Entity Framework - 混合模型优先和数据库优先方法?

c# - 动态 Linq to 实体排序与分页

c# - 我究竟做错了什么? wcf 和 Entity Framework

.net - 将列表/数组/集合传递到 WCF 数据服务 (OData) 服务操作中