Skip to content

JoinedSubclassMapping to pull base object without joins #2419

@fairking

Description

@fairking

NH v. 5.2.7, 5.3.0

I got a situation when I need to get a base object without any joins.
Is it possible?
If I remove abstract class I still get a query with joins to all derived tables.

Eg.

// Entities
public ~~abstract~~ class Document
{
    public virtual Guid Id { get; set; }
    public virtual string Name { get; set; }
}
public class Order : Document
{
    public virtual decimal OrderTotal { get; set; }
}
public class Invoice : Document
{
    public virtual decimal InvoiceTotal { get; set; }
}

// Mappings
public class DocumentMapping : ClassMapping<Document>
{
	public DocumentMapping()
	{
                Table("documents");
		Id(x => x.Id);
		Property(x => x.Name);
	}
}
public class OrderMapping : JoinedSubclassMapping<Order>
{
	public OrderMapping()
	{
                Table("orders");
		Key(x => x.Column("Id"));
		Property(x => x.OrderTotal);
	}
}
public class InvoiceMapping : JoinedSubclassMapping<Invoice>
{
	public InvoiceMapping()
	{
                Table("invoices");
		Key(x => x.Column("Id"));
		Property(x => x.InvoiceTotal);
	}
}

The following code:

var list = _session.Query<Document>().ToList();

Produces the following query:

select 
    doc.id, 
    doc.name, 
    inv.invoice_total, 
    ord.order_total, 
    case 
        when inv.id is not null then 1 
        when ord.id is not null then 2 
        when doc.id is not null then 0 
    end as clazz_ 
from documents doc 
    left outer join invoices inv on doc.id=inv.id 
    left outer join orders ord on doc.id=ord.id

The same applied to the references:

public class Customer
{
    public virtual Document ParentDocument { get; set; } // two joins

    public virtual Invoice InitialInvoice { get; set; } // one join to [invoices] table

    public virtual ICollection<Document> AllDocuments { get; set; } // two joins

    public virtual ICollection<Order> AllOrders { get; set; } // one join to [orders] table
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions