ASP MVC Lambda Expressions or Request Extensions?

I am using Model Factory to query related objects from the requesting model. The result is the ViewModel from the given object.

To get data

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

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

      

Process data

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>();

      

Question

Having many different Factories that have a "Member" view model. This is really bad style because I have code redundancy. Is there a way to execute the function in the request like:

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>();

      

Read a lot about the expressions I tried were unsuccessful. It would be nice if you point me in the right direction.

+3


source to share


1 answer


Thanks to Thomas Petrichuk, who said these worthy words:

Declaring a lambda expression to be used in a request is straight forward because it is no different from any other C # lambda expressions. The query is more interesting because it uses two extensions of different methods. The first method, called ToExpandable , creates a thin wrapper around the DLINQ table object. Thanks to this wrapper, you can use a second method called Invoke , which extends the expression class to invoke the lambda expression, doing its best to translate the query to T-SQL. This works because when converting to an Expression Tree, the wrapper replaces all occurrences of the Invoke method across the expression trees of the lambda expression being called and passes those expressions to DLINQ, which can convert the extended query to T-SQL.



And reading this article should be helpful: http://tomasp.net/blog/linq-expand.aspx/

0


source







All Articles