views:

54

answers:

1

I had a linq-to-sql generated domain entity that I cast to the proper interface like so:

public IEnumerable<IApplication> GetApplications()
    {
        using (var dc = new LqDev202DataContext())
        {
            return dc.ZApplications.Cast<IApplication>().ToList();
        }
    }

However I renamed the linq-to-sql table without touching my partial class and the code still compiled.

The list had the right amount of elements, but they were all null.

Do I need to write a helper method to make sure this will work, or is there a compile time safe simple built-in way to do this in .net 3.5?

A: 

You can also use this to do casting with conversions if needed:

public static IEnumerable<TDest> CastAll<TItem, TDest>(this IEnumerable<TItem> items)
{
 var p = Expression.Parameter(typeof(TItem), "i");
 var c = Expression.Convert(p, typeof(TDest));
 var ex = Expression.Lambda<Func<TItem, TDest>>(c, p).Compile();

 foreach (var item in items)
 {
    yield return ex(item);
 }
}

From http://adventuresdotnet.blogspot.com/2010/06/better-more-type-safe-alternative-to.html

Maslow