I have an ASP.NET MVC application that uses the Entity Framework to retrieve data.
I need to convert Entites to Models before passing their View. Projecting can be very complex, but to make it simple:
public static IQueryable<UserModel> ToModel(this IQueryable<User> users)
{
return from user in users
select new UserModel
{
Name = user.Name,
Email = user.Email,
};
}
This can be used in the controller as follows:
return View(Repository.Users.ToModel().ToList());
Very well. But what if I want to use this projection inside another? Example:
public static IQueryable<BlogPostModel> ToModel(this IQueryable<BlogPost> blogs)
{
return from blogs in blogs
select new BlogPostModel
{
Title = blog.Title,
Authors = blog.Authors.AsQueryable().ToModel(),
};
}
(suppose that there can be more than one author on a blog, and it is of type User).
Can the projections be separated in any way and reused inside others?
source
share