gpt4 book ai didi

sql - ASP MVC Lambda 表达式或查询扩展?

转载 作者:行者123 更新时间:2023-12-02 04:51:49 25 4
gpt4 key购买 nike

我正在使用模型工厂从请求模型中查询相关实体。结果是来自给定实体的 ViewModel。

获取数据

var posts = _postRepo.GetCommunityPosts(Id); // get an iqueryable

ICollection<PostViewModel> result = await ModelFactory.PostFactory(posts, take, skip); //using the ModelFactory to create the viewmodel

处理数据

public async Task<ICollection<PostViewModel>> PostFactory(IQueryable<TRDPost> posts)
{
return await posts.Select(a => new PostViewModel //the viewmodel
{
// simple properties
Created = a.Created,
Body = a.Body,
Id = a.Id,
// related viewmodels
Member = new MemberViewModel
{
// Member related stuff here
// a lot of properties and also related viewmodels here
}
}
}).ToListAsync<PostViewModel>();

问题

有很多不同的工厂,它们都有“成员” View 模型。这确实是一种糟糕的风格,因为我有大量的代码冗余。有没有办法在查询中执行函数,例如:

public async Task<ICollection<PostViewModel>> PostFactory(IQueryable<TRDPost> posts)
{
return await posts.Select(a => new PostViewModel //the viewmodel
{
// simple properties
Created = a.Created,
Body = a.Body,
Id = a.Id,
// related viewmodels
Member = GetMemberViewModel(a) // is this possible?
}
}).ToListAsync<PostViewModel>();

阅读了很多关于表达式的文章,但我尝试过的都没有成功。如果您能为我指出正确的方向,那就太好了。

最佳答案

感谢 Tomas Petricek 说了这句话:

Declaration of lambda expression that will be used by the query is straightforward, because it isn't different than any other C# lambda expressions. The query is more interesting because it uses two extension different methods. First method called ToExpandable creates a thin wrapper around the DLINQ Table object. Thanks to this wrapper you can use second method called Invoke that extends the Expression class to invoke the lambda expression while making it still possible to translate query to T-SQL. This works because when converting to the expression tree, the wrapper replaces all occurrences of Invoke method by expression trees of the invoked lambda expression and passes these expressions to DLINQ that is able to translate the expanded query to T-SQL.

阅读这篇文章一定会有帮助:http://tomasp.net/blog/linq-expand.aspx/

关于sql - ASP MVC Lambda 表达式或查询扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27474442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com