C# + LINQ + ADO.NET EF , join 2 tables and return everything without specifying all fields manually

ado.net c# entity-framework linq

Question

I have a simple LINQ query on ADO.NET Entity Framework as follows

var result = 
  from itemA in TableA
  join itemB in TableB on itemA.ID = itemB.ID
  select ??????

I am trying to select everything from itemA and itemB without specifying all the TableA and TableB.

anything thoughts???

Accepted Answer

Is this what you need?

    var result = from itemA in TableA 
                 join itemB in TableB on itemA.ID equals itemB.ID
                 select new { itemA, itemB };

Alternately, you could declare a result class that helps you build the result object without specifying all the fields:

    class ItemAB
    {
        public ItemAB(ItemA a, ItemB b)
        {
            FieldA1 = a.FieldA1;
            FieldA2 = a.FieldA2;
            FieldB1 = b.FieldB1;
            FieldB2 = b.FieldB2;

        }
        public int FieldA1 { get; private set; }
        public int FieldA2 { get; private set; }
        public int FieldB1 { get; private set; }
        public int FieldB2 { get; private set; }
    }

    var result = from itemA in TableA 
                 join itemB in TableB on itemA.ID equals itemB.ID
                 select new ItemAB(itemA, itemB);

Popular Answer

From your link query it looks like you have 2 tables with a one to one relationship.

If so, the way to do it is to configure your entity model such that two tables are merged into one entity. For details see:

http://blogs.msdn.com/simonince/archive/2009/03/23/mapping-two-tables-to-one-entity-in-the-entity-framework.aspx



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why