在我的数据库中,几乎每个表都有自己的翻译表。即Sports有SportsTranslations表,列有:SportId,LanguageId,Name。目前我正在翻译:
int[] defaultLanguages = { 1, 3 };
var query = from s in dc.Sports
select new
{
sportName = s.SportsTranslations.Where(st => defaultLanguages.Contains(st.LanguageID)).First()
};
我想知道是否可以实现某种通用方法,所以我可以像这里一样重构代码:
var query = from s in dc.Sports
select new
{
sportName = s.SportsTranslations.Translate()
};
答案 0 :(得分:0)
解决。这是我写的静态方法:
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));
}
}
}