C#如何序列化system.linq.expressions?

时间:2013-08-09 08:51:51

标签: c# .net wcf entity-framework-5 iqueryable

我正在研究winRT和实体框架(对SQL),它们之间进行通信的层是WCF服务。在实体框架中,我使用的是Repository Pattern,我有方法:

public IQueryable<User> GetBySearch(Expression<Func<User, bool>> search)
{
    return this.Context.Users.Where(search);
}

一切正常,但是当我把它添加到WCF

[OperationContract]
IQueryable<User> GetUserBySearch(Expression<Func<User, bool>> search);

public IQueryable<User> GetUserBySearch(Expression<Func<User, bool>> search)
{
    IUser user = new UserRepository();
    return user.GetBySearch(search);
}

但是Expression不能序列化的问题,因此,WCF无法序列化它。所以我想继承它并将其作为[Serializable],但问题是它是一个密封的类。

有人可以帮我解决问题吗?

3 个答案:

答案 0 :(得分:1)

如果你正在使用Entity Framework,那么WCF不能与Iqueryable和lambdas一起玩。这是一个快速而肮脏的解决方案,可以根据您的需求进行调整。

将服务合同更改为

[OperationContract]
IEnumerable<User> GetEventBySearch(UserCriteria search);

其中UserCriteria是一个DataContract,它包含您需要的每个搜索条件的属性 - 例如:

[DataContract]
public class UserCriteria
{
    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public string Email { get; set; }

    // add a property for each search criteria....
}

服务实施:

public IEnumerable<User> GetEventBySearch(UserCriteria search)
{
    IUser user = new UserRepository();
    Expression<Func<User, bool>> criteria = BuildExpression(search);

    return user.GetBySearch(criteria).AsEnumerable();
}

private Expression<Func<User, bool>> BuildExpression(UserCriteria search)
{
    // build lambda expression here
}

答案 1 :(得分:0)

将表达式更改为Func,您可以使用BinaryFormatter或其他序列化程序按照您的意愿将其序列化

答案 2 :(得分:0)

您可以使用ServicePredicateBuilder序列化表达式。 http://www.codeproject.com/Articles/851187/ServicePredicateBuilder-for-creating-Serializable