1

我在为 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;
}
4

2 回答 2

1

我找到了另一种使用通用方式返回相同结果的方法。

    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 结果 = QueryableTable.IncludeTranslation(t => t.FieldToTranslate);

于 2013-05-14T19:19:58.653 回答
1

试试这个(我不得不猜测类名是 CFG_ARTICLE 和 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);
于 2013-05-13T14:21:10.077 回答