Search code examples
c#asp.net-mvcjoinsimple.data

Simple.Data One Direction Join on a Table Twice


I have a Users table and a Messages table. The Messages table has two foreign key references to the Users table, "To_Id" and "From_Id" both pointing to User.Id. I want to write a query that will return the messages and allow me to get the Username property from both the User represented by the To and From relations. Here's what I have so far:

dynamic sender;
dynamic recipient;
var messages= db.Messages.All(db.Messages.To_Id == currentUser.Id || db.Messages.From_Id == currentUser.Id)
    .Join(db.Users.As("Sender"), out sender).On(sender.Id == db.Messages.From_Id)
    .Join(db.Users.As("Recipient"), out recipient).On(recipient.Id == db.Messages.To_Id)
return messages;

The result of this query gives me the correct Messages count, but the To_Id and From_Id columns disappear and the Sender and Recipient column names also do not appear. I tried looking at the docs, the source on github and this question here: Simple.Data - how to bi-drectionally join on the same table twice without any success yet. Any ideas?


Solution

  • I don't know what could be happening to your To_Id and From_Id columns, but if you want to eager-load the Users rows, you need to add With clauses:

    dynamic sender;
    dynamic recipient;
    var messages= db.Messages.All(db.Messages.To_Id == currentUser.Id || db.Messages.From_Id == currentUser.Id)
        .Join(db.Users.As("Sender"), out sender).On(sender.Id == db.Messages.From_Id)
        .Join(db.Users.As("Recipient"), out recipient).On(recipient.Id == db.Messages.To_Id)
        .With(sender)
        .With(recipient);
    return messages;
    

    As for the missing columns, have you tried looking at the Trace to see the SQL that's being executed for the query? That might help to shed some light.