tags:

views:

27

answers:

2

I've 2 tables with same column's name, for example, both table A and table B has column's name "Test". I want to select column Test from both table A and B to entity class. How can I do this?

A: 

It sounds like you want the two entities of TableA and TableB merged into a new object. You can use the .Select() extension method to create a new anonymous type, or into a class that you already have defined.

The requirement here is that you've got to find a common attribute between TableA and TableB. Here I assume you've got something like ID to match them together.

Anonymous Type

 var mergedTests =  from a in db.TableA
                    join b in db.TableB on a.CommonID equals b.CommonID
                    select new 
                           { TestFromA = a.Test, TestFromB = b.Test }
                    .ToList();

Existing Class

 List<MyCustomTests> mergedTests =  from a in db.TableA
                    join b in db.TableB on a.CommonID equals b.CommonID
                    select new MyCustomTests 
                       { TestName= a.Test, ShortName= b.Test }
                    .ToList();
p.campbell
This is not I want, I want to select column Test from both table A and B to same row but different column name. E.g. TestA and TestB are in same row.
In The Pink
A: 
class Program
{
    static void Main(string[] args)
    {
        var A = new Data[] {
            new Data { Test = 1, Relation = 1 },
            new Data { Test = 2, Relation = 2 },
            new Data { Test = 3, Relation = 3 },
            new Data { Test = 4, Relation = 4 },
            new Data { Test = 5, Relation = 5 },
        };

        var B = new Data[] {
            new Data { Test = 2, Relation = 2 },
            new Data { Test = 3, Relation = 3 },
            new Data { Test = 5, Relation = 5 },
        };

        var res = from a in A
                  join b in B on a.Relation equals b.Relation
                  select new { TestA = a.Test, TestB = b.Test };
    }
}

class Data
{
    public int Test;
    public int Relation;
}
zerkms