OrmLite join table by multiple columns

Viewed 120

With OrmLite how can I join a table by multiple columns?

I have Notes table that can have data for either QutoeHeader or OrderHeader so I tried to join and use SelectMulti() like this:

var userSpecificQuery =
    _db
        .From<Customer>()
        .Where(x => x.SalesRepresentativeId == userId)
        .LeftJoin<Customer, QuoteHeader>((c, q) => c.Id == q.CustomerId)
        .LeftJoin<Customer, OrderHeader>((c, o) => c.Id == o.CustomerId)
        .LeftJoin<OrderHeader, QuoteHeader, Notes>((oh,qh, n) => oh.Id == n.OrderId || qh.Id == n.QuoteId)
    ;


var userSpecificRecords = 
    _db.SelectMulti<Customer, QuoteHeader, OrderHeader, Notes>(userSpecificQuery);

But I get error:

table name "quote_header" specified more than once

I want to join all record that match either OrderId or QuoteId. I tried a few different ways and get same error. Is this possible?

edit:

Here is note model

public class Notes : BaseModel
{
    [AutoIncrement]
    public long Id { get; set; }
    [ForeignKey(typeof(QuoteHeader))]
    public long? QuoteId { get; set; }
    [ForeignKey(typeof(OrderHeader))]
    public long? OrderId { get; set; }
    public string NoteText { get; set; }
}
1 Answers

Instead of joining on QuoteHeader multiple times, move the condition into Where:

db.From<Customer>()
  .Where(x => x.SalesRepresentativeId == userId)
  .LeftJoin<Customer, QuoteHeader>((c, q) => c.Id == q.CustomerId)
  .LeftJoin<Customer, OrderHeader>((c, o) => c.Id == o.CustomerId)
  .LeftJoin<OrderHeader, Notes>((oh, n) => oh.Id == n.OrderId)
  .Where<OrderHeader,QuoteHeader,Notes>((oh,qh,n) => oh.OrderId != null || qh.Id == n.QuoteId)
Related