tags:

views:

44

answers:

2

I have two tables, with foreign key. linq to sql class generated for me classes. now i want make linq select with join, what will be result of join? is where any way to generate class, for that result? want get something like

IEnumerable<par_of_class1+part_of_class2>. 

thx

+1  A: 

It depends on the scope for what you need this "type" for.

If you only need access to this result in a particular method, you can project the result into an anonymous type (as they only have method scope).

Example:

var result = (from a in tablea join b in tableb
            on a.key equals b.key
            select new { 
                PropertyOne = a.Something, 
                PropertyTwo = b.Something 
             }).SingleOrDefault();

In that example, result will be an anonymous type, containing two properties, PropertyOne and PropertyTwo.

Note, before calling SingleOrDefault, the query is an IQueryable<T>, so you can choose to project the result set into a collection, by using .ToList().

Modify the select new (called 'projection') to contain whatever you want.

If you need access to this type outside the method, instead of select new { }, do this:

select new SomeClass { ... } // projection into concrete class

And project the fields into that class (which can have the appropriate accessibility modifier).

Also (on a side note), please don't forget to go back and accept some of your answers (including this one, if it's correct), as it will result in more people providing you with assistance.

HTH

RPM1984
A: 

RPM1984 is correct. Here is the other way to do join that which, while more cumbersome, is worth mentioning:

TableOne
    .Join(
        TableTwo,
        x => x.TableOneID, //selector for the outer table (TableOne)
        x => x.TableOneFK, //selector for the inner table (TableTwo).  These values are what the tables are joined on
        (o,i) => new { Outer = o, Inner = i, Property = o.Property } //new anonymous class where o is a record from TableOne, and i is a record from TableTwo
    );

You don't have to return an anonymous class if you don't want to though. The return of a join really can be whatever you want it to be. you could just return 'o.Property' if that's all you want, or just 'o'. Feel free to play around with it to return whatever it is you want!

diceguyd30