Tuesday, September 8, 2009

Passing Anonymous Types as Method Parameters with LINQ to SQL

I was looking for a way to Pass Anonymous types as parameters to a method as I didnt want to create code redundancy. Based on the research, I found out that Creating a Class with the same properties with that of the anonymous type would do the trick. Here's an Example:


public class articleitems
{
public string title { get; set; }
public string web_blurb { get; set; }
public DateTime publish_date { get; set; }
public string webauthor { get; set; }
public string body { get; set; }
}


using this class in your LINQ to SQL query, this is what u get:


List articlelist = (from cat in db.articleposts
where cat.columntypeid == 1
select new articleitems
{
title = cat.title,
web_blurb = cat.web_blurb,
publish_date = cat.publish_date,
webauthor = cat.authorname,
body = cat.body
}).ToList();



The returned List can now be used in your method:
GetItems(articlelist);

Yippy!