c# - 不明确的 IQueryable<T>.Where 和 IEnumerable<T>.Where 扩展方法

标签 c# linq generics entity-framework-6 extension-methods

我正在尝试使用以下扩展方法为我的实体覆盖所有 Where() 方法:

public static IQueryable<T> Where<T>(this IQueryable<T> source, Expression<Func<T, bool>> predicate)
{
    throw new SecurityException("Use the security SafeWhere method");
}

但是当我使用 context.EntitiesX.Where() 时,我得到了错误:The call is ambiguous between Queryable(IQueryable, Expression>) 和 Enumerable(IEnumerable, Expression>)

我该如何解决?此外,我希望该扩展方法只影响实现特定接口(interface)的实体,我已经尝试通过指定接口(interface)类型而不是通用 T 来实现,但这不起作用。

最佳答案

诀窍是为您的扩展方法提供比第 3 方(系统)方法更高的优先级。

假设你的代码结构是这样的

MyExtensions.cs

using System;
// ... other 3rd party usings

namespace MyExtensionsNamespace
{
    public static class MyExtensions
    {
        public static IQueryable<T> Where<T>(this IQueryable<T> source, Expression<Func<T, bool>> predicate)
        {
            throw new SecurityException("Use the security SafeWhere method");
        }
        // ...
    }
}

MyEntity.cs

using System;
using System.Linq;
// ... other 3rd party usings
using MyExtensionsNamespace;

namespace MyEntitiesNamespace
{
    // ...
}

您只需像这样在命名空间声明之后移动您的命名空间 usings

MyEntity.cs

using System;
using System.Linq;
// ... other 3rd party usings

namespace MyEntitiesNamespace
{
    using MyExtensionsNamespace;
    // ...
}

附言编译器错误消息具有误导性。它是在使用扩展方法语法时生成的。对于 LINQ 语法,错误是不同的

Error CS1940 Multiple implementations of the query pattern were found for source type 'DbSet'. Ambiguous call to 'Where'.

关于c# - 不明确的 IQueryable<T>.Where 和 IEnumerable<T>.Where 扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33678000/

相关文章:

c# - C# 中的 CodePointAt 等价物

C#:Resharper 的替代品,C# 版本

java - 如何返回作为参数给出的相同 Collection 类型,但具有不同的元素类型?

java - 在这种情况下如何在 java 泛型中使用多个边界

c# - 如何传递要使用 LINQ 调用的函数委托(delegate)?

c# - 使用以下语句有什么好处?

c# - 在派生类 C# 中扩展嵌套类

c# - 从 MVC View 保存多个对象

c# - LINQ - 展平嵌套序列,使其与父序列连接

c# - 连接 null 以查找缺失的元素