我在创建IQueryable的扩展方法时遇到问题,该方法将包含Linq查询中指定列的转换。
假设我有以下查询。 我想在CFG_Article IQueryable上调用一个方法IncludeTranslation,指定我想要获取翻译的列。 有人可以帮助我朝正确的方向发展。
var translations =
from t in UoW.CFG_TRANSLATION.GetAll()
select t;
var result = (
from a in UoW.CFG_ARTICLE.GetAll()
select new
{
a,
translation = translations
.Where(t=> t.TR_TEXT == a.AR_NAME).FirstOrDefault()
});
到目前为止,我所提出的是下面的代码,但这不会编译。
public static IQueryable IncludeTranslation<T>(
this IQueryable<T> query,
Expression<Func<t, bool>> fieldToTranslate)
{
// this will get an IQueryable of CFG_TRANSLATION
var translations = GetTranslations();
var result = (
from q in query
select new
{
q,
translation = translations
.Where(t=> t.TR_TEXT == fieldToTranslate)
.FirstOrDefault()
});
// even better is to return all fields from query
// + the TR_TRANSLATION field from the translations table
return result;
}
答案 0 :(得分:1)
试试这个(我不得不猜测类名是CFG_ARTICLE&amp; CFG_TRANSLATION - 根据需要替换)
public static IQueryable IncludeTranslation(
this IQueryable<CGF_ARTICLE> query,
Func<CFG_ARTICLE, CFG_TRANSLATION, bool> fieldToTranslate)
{
var translations = GetTranslations();
var result =
from a in query
select new
{
a,
translation = translations
.Where(t => fieldToTranslate(a, t))
.FirstOrDefault()
};
return result;
}
像这样打电话
var result = query.IncludeTranslation(
(article, translation) => article.TR_TEXT == translation.AR_NAME);
答案 1 :(得分:1)
我找到了另一种使用Generic Way返回相同结果的方法。
public static IQueryable IncludeTranslation<S>(this IQueryable<S> source, Expression<Func<S, string>> keyField) where S : class { IQueryable<CFG_TRANSLATION> translations = GetTranslations(); var trans = source.GroupJoin(translations, keyField, t => t.TR_TEXT, (s, t) => new { Source = s, Translations = t }); var result = trans.Select(t => new { Source = t.Source, Translation = t.Translations .FirstOrDefault() }); return result; }
也许有人可以将其用作溶剂
这可以称为
var Result = QueryableTable.IncludeTranslation(t =&gt; t.FieldToTranslate);