How to reuse projections in Entity Framework?

廉价感情. 提交于 2019-12-04 07:14:20

Here's something that actually works (in a simple test application) to only select the requested fields:

namespace Entities
{
    public class BlogPost
    {
        public virtual int Id { get; set; }
        public virtual string Title { get; set; }
        public virtual DateTime Created { get; set; }
        public virtual ICollection<User> Authors { get; set; }
    }

    public class User
    {
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
        public virtual string Email { get; set; }
        public virtual byte[] Password { get; set; }
        public virtual ICollection<BlogPost> BlogPosts { get; set; }
    }
}

namespace Models
{
    public class BlogPostModel
    {
        public string Title { get; set; }
        public IEnumerable<UserModel> Authors { get; set; }
    }

    public class UserModel
    {
        public string Name { get; set; }
        public string Email { get; set; }
    }

    public static class BlogPostModelExtensions
    {
        public static readonly Expression<Func<BlogPost, BlogPostModel>> ToModelConverterExpression =
            p =>
            new BlogPostModel
            {
                Title = p.Title,
                Authors = p.Authors.AsQueryable().Select(UserModelExtensions.ToModelConverterExpression),
            };

        public static readonly Func<BlogPost, BlogPostModel> ToModelConverterFunction = ToModelConverterExpression.Compile();

        public static IQueryable<BlogPostModel> ToModel(this IQueryable<BlogPost> blogPosts)
        {
            return blogPosts.Select(ToModelConverterExpression);
        }

        public static IEnumerable<BlogPostModel> ToModel(this IEnumerable<BlogPost> blogPosts)
        {
            return blogPosts.Select(ToModelConverterFunction);
        }
    }

    public static class UserModelExtensions
    {
        public static readonly Expression<Func<User, UserModel>> ToModelConverterExpression =
            u =>
            new UserModel
            {
                Name = u.Name,
                Email = u.Email,
            };

        public static readonly Func<User, UserModel> ToModelConverterFunction = ToModelConverterExpression.Compile();

        public static IQueryable<UserModel> ToModel(this IQueryable<User> users)
        {
            return users.Select(ToModelConverterExpression);
        }

        public static IEnumerable<UserModel> ToModel(this IEnumerable<User> users)
        {
            return users.Select(ToModelConverterFunction);
        }
    }
}

To test it without actually creating a database:

var blogPostsQuery = (
    from p in context.BlogPosts
    where p.Title.StartsWith("a")
    select p).ToModel();
Console.WriteLine(((ObjectQuery)blogPostQuery).ToTraceString());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!