开发者

Help with linq2sql generic lambda expression

开发者 https://www.devze.com 2022-12-15 16:51 出处:网络
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:

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()
                   };


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));
            }
        }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消