简体   繁体   中英

Does WCF OData Service Support Projection?

I'm using WCF OData service as my application Data Provider.OData service expose a entity that I don't want to get whole entity,I create LINQ query to get projection from this Entity. But i have error in OData Service.This is my code:

from n in NewsInfos
select new NewsInfos
{
    n.NewsId,
    n.NewsTitle,
    n.NewsLead,
    n.NewsDate
};

This is entire code:

[System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    public class NewsDataService : DataService<NewsODataModel>
    {
        public static void InitializeService(DataServiceConfiguration config)
        {
            config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
            config.DataServiceBehavior.AcceptProjectionRequests = true;
        }
    }

Yes, WCF Data Services and OData support projection. Projection is codified in the URL with the $select system query option, eg: http://services.odata.org/Experimental/OData/OData.svc/Products?$select=Name&$format=json . The LINQ Provider in the client bits enable this similarly to what you've shown in your example. Here is one such example:

using System;
using System.Data.Services.Client;
using System.Linq;

namespace Scratch
{
    public class Program
    {
        public static void Main()
        {
            var context = new DataServiceContext(new Uri("http://services.odata.org/OData/OData.svc/"));
            var categories = context.CreateQuery<Category>("Categories").Select(c => new { c.Name });
            Console.WriteLine("context.Categories.Where(...): {0}", categories);
            foreach (var category in categories)
            {
                Console.WriteLine(category.Name);
            }
        }
    }

    public class Category
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
}

One thing to consider with projection is that the magic in our client-side bits frequently requires you to use anonymous objects (hence the new { c.Name } ).

Your error may be unrelated; if you're still getting the error after reading this can you update your service to return verbose errors as per http://blogs.msdn.com/b/phaniraj/archive/2008/06/18/debugging-ado-net-data-services.aspx ? My guess is that you may be missing the [DataServiceKey] attribute on NewsInfos .

Just return an anonymous object from your select and it should work.

from n in NewsInfos
select new
{
    n.NewsId,
    n.NewsTitle,
    n.NewsLead,
    n.NewsDate
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM