***** Disclaimer ******
I may be the last person to figure this out, but oh well.
***** End Disclaimer ******
Today as I was further exploring the coolness that is Linq to Sql I ran into a little situation. I was creating a query where I wanted to use the columns form multiple tables to build an object. Since the results did not map 1 to 1 from a table to a object I figured I would have to do it the mapping the hard way. Here was the code I originally had.
var results = from c in DBContextInstance().Companies
join pc in DBContextInstance().ProgramControls on c.CoID equals pc.CoID
select new {c.CoID, c.CoDesc, pc.ProjectNotes, pc.ProjectManager};
List newList = new List< HybridObject >();
foreach ( var result in results )
{
HybridObject entity = new HybridObject
{
CompanyID = result.CoID,
CompanyDesc = result.CoDesc,
ProjectNotes = result.ProjectNotes,
ProjectManager = result.ProjectManager
};
newList.Add( entity );
}
After looking at the code above for a few minutes, I really, really did not like it. I knew there had to be a better way. So I started playing around with various ways to do this. I had a hunch that since I was creating a return value as an Anonymous type, I should be able to create a concrete type in its place. Sure enough, I could. With a little help from constructor initializers (sure you could also do this by creating a constructor that took in the values as well). Take a look at the new, cleaner code below.
var results = ( from c in DBContextInstance().Companies
join pc in DBContextInstance().ProgramControls on c.CoID equals pc.CoID
select new HybridObject
{
CompanyID = CoID,
CompanyDesc = CoDesc,
ProjectNotes = ProjectNotes,
ProjectManager = ProjectManager
} ).ToList();
Now if you ask me, the new code is much more concise and much simpler. It also does not waste CPU cycles, which is always a plus.
If anyone has a better way, please let me know.
Till next time,