views:

48

answers:

1

In my Database almost every table has its own translations table. I.e. Sports has SportsTranslations table with columns: SportId, LanguageId, Name. At the moment I'm taking translations like:

int[] defaultLanguages = { 1, 3 };
var query = from s in dc.Sports
            select new
                   {
                      sportName = s.SportsTranslations.Where(st => defaultLanguages.Contains(st.LanguageID)).First()
                   };

I wonder is it possible to implement some kind of generic method, so I could refactor code like here:

var query = from s in dc.Sports
            select new
                   {
                      sportName = s.SportsTranslations.Translate()
                   };
A: 

Solved. Here is the static method I written:

public static class Extras
{    
    public static T Translate<T>(this IEnumerable<T> table) where T : class
        {
            try
            {
                return table.Where(
                    t => defaultLanguages.Contains(
                        (int)t.GetType().GetProperty("LanguageID").GetValue(t, null)
                    )
                ).First();
            }
            catch (Exception)
            {
                throw new ApplicationException(string.Format("No translation found in table {0}", typeof(T).Name));
            }
        }
}
Leonid