2016-10-05 25 views
0

ModelFactoryクラスのメソッドを使用して、Object Initializerを使用する代わりにCommentWithUserDetailsのインスタンスを作成します。これはできますか?エンティティへFactoryメソッドをLINQのresultSelectorとして使用する方法Join

ExceptionMessage

LINQは方法を認識しない 方法 'WebApi.Models.CommentWithUserDetailsは(WebApi.Models.Comment、 WebApi.Models.ApplicationUser)を作成'、そしてこの方法は することはできませんストア式に変換されます。


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 
     }; 
    } 
} 

答えて

3

ではなくセレクタとしてメソッドを持つあなたが使用できるように、あなたが望む表現を返すことエクスプレッションを持っている必要がありますが、あなたはもちろんの方法(またはプロパティ)を書くことができます複数の場所で、それは:

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 
     }; 
    } 
} 

その後、Joinのための結果のセレクターにModelFactory.Createに渡すことができます。

0

はい、しかし。ファクトリメソッドを使用すると、linqをオブジェクトにしか使用できなくなります。クエリプロバイダは、ファクトリメソッドで何をすべきかを知りません。

初めて参加する場合は、.AsEnumerable()に電話して.Select(...)を使用してください。これは、これが機能します。あなたは合成能力を失います。

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

    return commentsWithUserDetails; 
} 
関連する問題