0

I have the following ViewModel:-

public class PostCommentReplyViewModel
{
     public List<POST> PostViewModel { get; set; }
     public List<COMMENT> CommentViewModel { get; set; }
     public List<REPLY> PostViewModel { get; set; }
}

And I have the following Action in my Controller:-

EntityDataModel db = new EntityDataModel();
var vm = new PostCommentReplyViewModel();
vm.PostViewModel = db.POSTs.Join(db.COMMENTs, b => b.user_id, c => c.user_id, (b, c) => b).ToList();
return View(vm);

Now this action return result of the two join tables but when I try to join the three tables into one result I get no result, How can I join the three tables into one result?

Linq Query Result to ViewModel

Thanks in advance :)

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Daniel
  • 403
  • 5
  • 13

2 Answers2

1

You are on the right way, you only need to add 3rd join:

vm.PostViewModel = db.POSTs
            .Join(db.COMMENTs, b => b.user_id, c => c.user_id, (b, c) => b)
            .Join(db.REPLYs, b => b.user_id, c => c.user_id, (b, c) => b)
            .ToList();

The reason of no results might be that you don't have data in all 3 tables that can be INNER JOINed by the same key.

Roman.Pavelko
  • 1,555
  • 2
  • 15
  • 18
  • It could also be easily converted into not inner join: https://stackoverflow.com/a/19294132/2283405 – balbelias Dec 25 '19 at 04:22
  • The problem was that the key is not the same in the query, the thing is that I am now trying to get multiple results from the same table in different forms of queries..e.g. Create another query with two tables joined and return the results as well – Daniel Dec 25 '19 at 11:57
0

Thanks for your help, the most helpful solution I found to the problem is to create separate queries from ViewModel and then I attach them to one variable by the magic word Union and then I ask the ViewModel for the objects.

Here is the magic:

var resultOne = db.POSTs.Join(db.COMMENTs, b => b.user_id, c => c.user_id, (b, c) => b);
var resultTwo = db.POSTs.Join(db.REPLYs, b => b.user_id, c => c.user_id, (b, c) => b);
var resultUnion = resultOne.Union(resultTwo);
vm.PostViewModel = resultUnion.ToList();
return View(vm);
Daniel
  • 403
  • 5
  • 13