【问题标题】:Consuming Service Operations of an ADO.NET Data Service from a .NET Client从 .NET 客户端使用 ADO.NET 数据服务的服务操作
【发布时间】:2009-10-13 10:10:41
【问题描述】:

我正在尝试构建一个包含大量实体和一些服务操作的 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 来遍历服务操作的返回数据。 这可能吗?应该是吧?

【问题讨论】:

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


    【解决方案1】:

    简单的东西你就知道了。

    只需要知道几件事:

    目前 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();
    }
    

    【讨论】:

    • 好的,但是如何从客户端调用“OrdersByRegion”操作?您是否必须手动构建 REST URL(例如server/service.svc/OrdersByRegion?regionId=1)?谢谢。
    • 嗨 Ciprian,是的,不幸的是你这样做了。 string.format 通常是最好用的。查看我的第一个代码示例,它演示了如何调用它
    • 抱歉,我忘记将此标记为已接受的答案(我正在浏览我的问题),当时我有点沮丧,因为 URL 不会自动构建。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 2012-12-07
    • 1970-01-01
    • 2011-09-10
    相关资源
    最近更新 更多