Using this answer I am now able to store my projection logic in an Expression and use it inside another projections.
However, when I started to implement this approch in my solution, I found out, that I am not able to use the stored Expression on a Navigation property which is a single FK (not a collection).
The following code demonstrates this issue:
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 single FK navigation property to a model using Expression?
This is currently possible in an overly complicated manner:
However, the generated SQL, while correct, is needlessly complicated and slow. As far as I know, there is not yet any way to directly get what you want, but I’ve been looking for the same thing, and I have a proof-of-concept patch for the open source to-be-EF-6.0 that I plan to submit for inclusion, see the discussion thread and the change.