HelloWorld1010 HelloWorld1010 - 2 months ago 6
C# Question

How to use a Factory method as resultSelector in LINQ Join

I would like to use a method from my ModelFactory class to create an instance of CommentWithUserDetails instead of using an Object Initializer. Can this be done?


ExceptionMessage

LINQ to Entities does not recognize the method
'WebApi.Models.CommentWithUserDetails Create(WebApi.Models.Comment,
WebApi.Models.ApplicationUser)' method, and this method cannot be
translated into a store expression.





public IEnumerable<CommentWithUserDetails> GetAllPostComments(int postId)
{
var commentsWithUserDetails = _context.Comments.Join(_context.Users,
c => c.UserId,
u => u.Id,
(comment, user) => _modelFactory.Create(comment, user));

return commentsWithUserDetails;
}





public class ModelFactory
{
public CommentWithUserDetails Create(Comment comment, ApplicationUser user)
{
return new CommentWithUserDetails
{
Id = comment.Id,
PostId = comment.PostId,
Body = comment.Body,
Name = user.Name
};
}
}

Answer

Rather than having a method as a selector, you'll need to have an expression, but you can of course write a method (or property) that returns the expression that you want, so that you can use it in multiple places:

public class ModelFactory
{
    public Expression<Func<Comment, ApplicationUser, CommentWithUserDetails>> Create()
    {
        return (comment, user) => new CommentWithUserDetails
        {
            Id = comment.Id,
            PostId = comment.PostId,
            Body = comment.Body,
            Name = user.Name
        };
    }
}

You can then pass in ModelFactory.Create into the result selector for the Join.