我正在尝试使用以下扩展方法为我的实体覆盖所有 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
我该如何解决?此外,我希望该扩展方法只影响实现特定接口(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/