【问题标题】:Non-recognized member in lambda expression of EF Core ThenInclude in Extension methodEF Core 的 lambda 表达式中无法识别的成员 ThenInclude 在 Extension 方法中
【发布时间】:2021-05-18 16:58:33
【问题描述】:

我正在尝试编写一个扩展方法来包含我的许多实体模型中存在的某个属性(文本元素,它们本身包含翻译集合)。

.Include 函数我没有问题:

public static IIncludableQueryable<T, IEnumerable<Translation>> IncludeTextBitWithTranslations<T>(this IQueryable<T> source, Expression<Func<T, TextBit>> predicate) where T: class
{
    var result = source.Include(predicate).ThenInclude(t => t.Translations);

    return result;
}

测试证明是成功的。

现在,在某些情况下,我的实体的所有文本都在一个子项中 - 例如 Article 实体有一个包含一些文本元素的 ArticleInfo 属性。所以我想我只需要做另一个扩展,那就是ThenInclude。有了一些不同,我终于明白了:

public static IIncludableQueryable<TEntity, ICollection<Translation>> ThenIncludeTextBitWithTranslations<TEntity, TPreviousProperty, TextBit>(this IIncludableQueryable<TEntity, TPreviousProperty> source, Expression<Func<TPreviousProperty, TextBit>> predicate) where TEntity: class
{
    var result = source.ThenInclude(predicate)
                       .ThenInclude(t => t.Translations);

    return result;
}

现在我得到了这个错误:

“TextBit”不包含“Translations”的定义,并且没有找到接受“TextBit”类型参数的扩展方法“Translations”

此错误出现在最后一个 lambda 表达式 t =&gt; t.Translations

这个错误对我来说非常奇怪,我一直在互联网上寻找有关此事的一些帮助,但我没有成功。

我尝试通过手动添加将类型强制为ThenInclude

var result = source.ThenInclude(predicate)
                   .ThenInclude<TEntity, TextBit, ICollection<Translation>>(t => t.Translations);

但没有成功。

有人知道为什么吗?

我在这里很茫然

【问题讨论】:

    标签: entity-framework linq .net-core extension-methods


    【解决方案1】:

    你在第二个(ThenIncludeTextBitWithTranslations&lt;TEntity, TPreviousProperty, TextBit&gt;)中有额外的类型参数TextBit,所以它被认为是泛型类型,而不是实际类型,删除它:

    public static IIncludableQueryable<TEntity, ICollection<Translation>> ThenIncludeTextBitWithTranslations<TEntity, TPreviousProperty>(this IIncludableQueryable<TEntity, TPreviousProperty> source, Expression<Func<TPreviousProperty, TextBit>> predicate) where TEntity: class
    {
        var result = source.ThenInclude(predicate).ThenInclude(t => t.Translations);
    
        return result;
    }
    

    【讨论】:

    • 就是这样......我的上帝,我只是复制了基本的 ThenInclude 结构并用我需要的东西替换了我的东西,却没有意识到我声明了一个新的通用类型隐藏我的实体......仍然我感觉它应该告诉我这个新的 Generic 类型隐藏了我的 Entity Type... 一直以来,我几乎要打我的屏幕啊,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多