动态修改LINQ to SQL Select语句的列 [英] Dynamically Modifying a LINQ to SQL Select Statement's Columns

查看:301
本文介绍了动态修改LINQ to SQL Select语句的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的应用程序构建一个REST-ful API.目前,我有这样的事情:
www.example.com/submissions/?format=json

I'm trying to build a REST-ful API for my app. Currently I have something like this:
www.example.com/submissions/?format=json

这将以JSON返回最新的十个提交.每个对象都有其详细信息,例如提交名称,创建日期,用户,正文等.

This will return latest ten submissions in JSON. Each object has its details, such as submission name, date created, user, body, etc.

我想做一些事情,例如:
www.example.com/submissions/?format=json&filter=name,user

I'd like to do something such as:
www.example.com/submissions/?format=json&filter=name,user

过滤器应发出返回相同结果的请求,但仅包括提及的详细信息,即每个对象仅具有名称和用户.

The filter should make the request to return the same result but to only include the details mentioned, i.e. each object will only have a name and user.

就JSON输出而言,这非常简单.我可以从数据库中加载所有列,并创建和序列化一个仅包含过滤器中列的对象.但是,我不想加载数据库中的所有列-我只想将要包含在响应中的列打扰我的数据库.

This is fairly straightforward in terms of the JSON output. I can load all the columns from the database and create and serialize an object that will only include the columns in the filter. However, I do not want to load all the columns in the database - I want to bother my database with only the columns that I will include in the response.

我想做这样的事情:

var result = from record in Submissions
             select
             {
                Name,
                Date,
                User,
                Body
             };

现在我有了result对象,该对象是IQueryable的,因此尚未对数据库进行任何调用.

Now I have the result object, which is IQueryable, so no call to database made yet.

然后,我应该检查filter查询字符串,并排除未提及的列.

Then, I should examine the filter querystring and exclude the columns that are not mentioned.

最后,我可以使用诸如
JavaScript.Serialize(result.ToList());

Finally, I can execute the select statement with something like
JavaScript.Serialize(result.ToList());

LINQ to SQL是否可能?

Is this possible with LINQ to SQL?

推荐答案

手动构建Select表达式树的另一种方法是

An alternative to building your Select expression tree by hand is Dynamic LINQ, which provides a Select method that takes a string:

var filter = "name,user";
var result = Submissions.Select("new(" + filter + ")");

然后将该字符串转换为表达式树,并传递给您的查询提供程序.

The string is then translated into an expression tree and passed on to your query provider.

这篇关于动态修改LINQ to SQL Select语句的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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