Search code examples
c#silverlightobservablecollectionwcf-ria-services

Loading WCF RIA Services Query results to an ObservableCollection


In my Silverlight app, after creating ADO.NET Entity Data Model and WCF RIA Services Domain Service Class, in a corresponding ProductService class I have a query operation that returns a collection of Product entities to the client, as follows:

public IQueryable<Product> GetProducts()
{
   return this.ObjectContext.Products;
}

Now I'm trying to read it in the client Silverlight app and load results to an ObservableCollection:

ProductContext pcontext = new ProductContext();
ObservableCollection<Prod> prAvs = pcontext.GetProductsQuery();

But getting an error:

Cannot implicitly convert type System.ServiceModel.DomainServices.Client.EntityQuery<MyTestApp.Web.Product> to System.Collections.ObjectModel.ObservableCollection<MyTestApp.Prod>

How could I fix that issue?


Solution

  • First problem:

    You should be using the client-side Products class generated for you by RIA services, not another class you define yourself.

    e.g you should have a collection of MyTestApp.Web.Product, not of MyTestApp.Prod objects.

    You will find the generated domain context in a hidden Generated_Code folder in your client project. Within that will be a MyTestApp.Web.g.cs file containing the client side context and any data objects (like MyTestApp.Web.Product).

    Second issue:

    You can't just cast a query to a collection.

    You need to use the query to load an entity change-set instead.

    var loadOperation = pcontext.Load(pcontext.GetProductsQuery());
    

    The result (when the load completes) is an entity collection in the returned loadOperation object. You can use the entity collection immediately, but it is initially empty.