Querying relationships that use table-per-hierarchy inheritance RRS feed

  • Question

  • I have an Organization entity that has many OrganizationalAttributes .  I'm using TPH inheritance to create real entities for those OrganizationalAttributes... so I've got 3 entities (Branch, Category, Component) that inherit from OrganizationalAttributes.

    I'm not exactly sure how to query for only Branches, for example... my LINQ is as follows:

     q = from
    in entities.Organization .Include("OrganizationalAttributes" ) select o;

    I can't exactly .Include("Branch") because the Organization entity is a many-to-many to OrganizationalAttributes, not branches explicitly.  Is there some other syntax (maybe using OfType) that I'm able to do this?

    The technique below works, but I'm not entirely happy with it.  I would rather just get back an Organization that has OrganizationalAttributes that are of type Branch, not some hybrid object that I have to further manipulate to get what I want (I would have to add the branches back to the Organization and return it).

     q3 = from
                 Organization = o,
                 Branches = o.OrganizationalAttributes.OfType<Branch>()
    • Edited by langdonx Thursday, December 3, 2009 2:59 PM formatting got jacked
    Thursday, December 3, 2009 2:45 PM


  • Hello,

    I don’t think we can combine the Include and OfType methods to accomplish this task.  Currently, the Include method cannot filter certain Inheritance. 

    Maybe you can refer to the following workaround if you want to get Organization entities instead of anonymous type objects. 

    Add a custom property to the Organization entity
        public partial class Organization


            public IEnumerable<Branch> Branches { get; set; }


    Then we use this query:
    var query = (from o in context.Organization

                 select new { Organization = o, Branches = o.OrganizationAttributes.OfType<Branch>() }).AsEnumerable().

                 Select(o => { o.Organization.Branches = o.Branches; return o.Organization; });

    Here I used multiple-line lambda expression.


    Best Regards,
    Lingzhi Sun

    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Monday, December 7, 2009 6:48 AM