C#中如何序列化system.linq.ex pressions? [英] C# How to serialize system.linq.expressions?

查看:335
本文介绍了C#中如何序列化system.linq.ex pressions?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在WinRT中和实体框架(到SQL),他们之间通信的层工作的WCF服务。在实体框架我使用存储库模式,我有方法:

I am working on winRT and entity framework (to SQL), the layer that communicates between them is WCF Service. In the entity framework I am using the Repository Pattern and I have the method:

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

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

Everything works fine, but when I add it to 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);
}

但是,防爆pression不是可序列化的问题,因此,WCF不能序列化。因此,我认为,从它继承并使其[Serializable接口]但问题在于它是一个密封类。

But the problem that Expression is not serializable, therefore, WCF can't serialize it. So I thought to inherit from it and make it [Serializable] but the problem that it is a sealed class.

有人可以帮助我解决这个问题?

Can someone help me to solve the problem?

推荐答案

WCF不与IQueryable的和lambda表达式,如果你使用的是实体框架打好。这是一个快速和肮脏的解决方案,使其适应您的需求。

WCF doesn't play well with Iqueryable and lambdas if your are using Entity Framework. This is a quick and dirty solution, adapt it to your needs.

更改服务合同

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

在哪里UserCriteria是包含一个属性,你需要每一个搜索条件的DataContract - 例如:

Where UserCriteria is a DataContract that contains a property for every search criteria that you need - example:

[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
}

这篇关于C#中如何序列化system.linq.ex pressions?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆