无法序列化“System.Linq.Enumerable…”类型的参数使用WCF、LINQ、JSON时

无法序列化“System.Linq.Enumerable…”类型的参数使用WCF、LINQ、JSON时,linq,wcf,json,linq-to-objects,Linq,Wcf,Json,Linq To Objects,我有WCF服务。它使用Linq从字典中选择对象。对象类型很简单: public class User { public Guid Id; public String Name; } 字典中存储了这些信息的集合 我想要一个WCF OperationContract方法,如下所示: public IEnumerable<Guid> GetAllUsers() { var selection = from user in list.Values se

我有WCF服务。它使用Linq从字典中选择对象。对象类型很简单:

public class User 
{
   public Guid Id;
   public String Name;
}
字典中存储了这些信息的集合

我想要一个WCF OperationContract方法,如下所示:

public IEnumerable<Guid> GetAllUsers()
{
    var selection = from user in list.Values
        select user.Id;
     return selection;
}

我有没有办法避免创建/实例化列表?

您需要向WCF方法传递可互操作的集合

WCF最适合使用简单类型和数组

从客户端传入一个数组,然后将其转换为服务中的IEnumerable

像IEnumerable这样的东西是不可互操作的,这正是WCF试图做到的


可能有一种方法可以绕过已知类型,但我始终努力使我的组件尽可能灵活。

不,必须从web服务返回具体的类。制作返回类型列表并完成它

您必须使用ServiceKnownTypes属性

using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace Test.Service
{
    [ServiceContract(Name = "Service", Namespace = "")]
    public interface IService
    {
        [OperationContract]
        [WebInvoke(
            Method = "GET",
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json)]
        [ServiceKnownType(typeof(List<EventData>))]
        IEnumerable<EventData> Method(Guid userId);
    }
}

基本上,你需要知道你返回的具体类型。很简单。

我想我并不是想发一个IEnumerable。我真正想要提供的是一个guid列表。但我不想为了实现这一点而做不必要的铸造。事实上,我可以将方法的返回类型更改为列表,然后创建一个新的列表,将选择传递到列表构造函数中——这很好,客户机以我想要的方式获取列表。很简单。我希望显式创建列表是不必要的。IEnumerable只是一个接口,说它不可互操作并不完全正确,因为它依赖于实现方法返回的IEnumerable的初始化类型。我使用IEnumerable作为服务操作的返回,没有任何问题,但关键是操作的返回值必须正确初始化。MattK-那么我如何使用linq to对象来执行查询,从而生成可以从WCF公开方法返回的IEnumerable?
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace Test.Service
{
    [ServiceContract(Name = "Service", Namespace = "")]
    public interface IService
    {
        [OperationContract]
        [WebInvoke(
            Method = "GET",
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json)]
        [ServiceKnownType(typeof(List<EventData>))]
        IEnumerable<EventData> Method(Guid userId);
    }
}