WCF Data Services 5.0 Workaround for returning POCOs?

好久不见. 提交于 2019-12-06 11:22:14

It is possible to return one or many primitive, complex, or entity types from a service operation.

  • A primitive type is what you'd expect: string, int, bool, etc.
  • A complex type is a class that doesn't have a unique key (a property named ID or the [DataServiceKey("<yourkeyhere>")] attribute)
  • An entity type is a class that does have a unique key

For instance:

using System.Data.Services;
using System.Data.Services.Common;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace Scratch.Web
{
    [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    public class ScratchService : DataService<ScratchContext>
    {
        public static void InitializeService(DataServiceConfiguration config)
        {
            config.SetEntitySetAccessRule("*", EntitySetRights.All);
            config.SetServiceOperationAccessRule("*", ServiceOperationRights.AllRead);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
            config.UseVerboseErrors = true;
        }

        [WebGet]
        public string GetPrimitive()
        {
            return "Success";
        }

        [WebGet]
        public IQueryable<string> GetPrimitives()
        {
            return new[] { "Success", "Hello World" }.AsQueryable();
        }

        [WebGet]
        public ComplexType GetComplexType()
        {
            return new ComplexType { Property1 = "Success", Property2 = "Hello World" };
        }

        [WebGet]
        public IQueryable<ComplexType> GetComplexTypes()
        {
            return new[] {
                           new ComplexType { Property1 = "Success", Property2 = "Hello World" },
                           new ComplexType { Property1 = "Success", Property2 = "Hello World" }
                       }.AsQueryable();
        }

        [WebGet]
        public EntityType GetEntityType()
        {
            return new EntityType { Property1 = "Success", Property2 = "Hello World" };
        }

        [WebGet]
        public IQueryable<EntityType> GetEntityTypes()
        {
            return new[] {
                           new EntityType { Property1 = "Success1", Property2 = "Hello World" },
                           new EntityType { Property1 = "Success2", Property2 = "Hello World" }
                       }.AsQueryable();
        }
    }

    public class ScratchContext { }

    public class ComplexType
    {
        public string Property1 { get; set; }
        public string Property2 { get; set; }
    }

    [DataServiceKey("Property1")]
    public class EntityType
    {
        public string Property1 { get; set; }
        public string Property2 { get; set; }
    }
}

Perhaps you're running into some other problem?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!