How to apply projection to FK property in Entity Framework?

Using this answer I can now save my projection logic in Expressionand use it in other projections.

However, when I started to implement this approach in my solution, I found out that I cannot use the stored Expressionin the Navigation property, which is the only FK (and not a collection).

The following code demonstrates this problem:

namespace Entities
{
    public class BlogPost
    {
        public virtual int BlogPostId { get; set; }
        public virtual string Title { get; set; }

        public virtual string NotUsed { get; set; }

        public virtual User Author { get; set; }
    }

    public class User
    {
        public virtual int UserId { get; set; }
        public virtual string Name { get; set; }
        public virtual string NotUsed { get; set; }

        public virtual ICollection<BlogPost> BlogPosts { get; set; }
    }
}

namespace Models
{
    public class BlogPostModel
    {
        public string Title { get; set; }
        public UserModel Author { get; set; }
    }

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

    public static class BlogPostModelExtensions
    {
        public static readonly Expression<Func<BlogPost, BlogPostModel>> ToModelConverterExpression =
            p =>
            new BlogPostModel
            {
                Title = p.Title,
                Author = null, //Problem!
                // I need to convert User (p.Author) to UserModel using UserModelExtensions.ToModelConverterExpression
            };
    }

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

Is it possible to convert one FK navigation property to a model with Expression?

+1
source share
1 answer

This is currently possible in an overly complex way:

p =>
new BlogPostModel
{
    ...,
    Author = new[] { p }.AsQueryable().Select(UserModelExtensions.ToModelConverterExpression).FirstOrDefault()
}

, SQL, , . , , , , open source to-be-EF- 6.0, , . .

+2

All Articles