LINQ to Entities通过接口属性

gar*_*eek 7 entity-framework business-logic-layer interface repository

我有一种情况,我想使用单个业务逻辑类在各种实体框架类上执行类似的操作.我已经定义了这些类在部分类文件中实现的接口.

但是,当我尝试针对这些接口方法编写LINQ to entities查询时,我得到一个NotSupportedException,因为查询没有直接使用类的属性,而是通过接口.

我想将繁重的工作保留到数据库层,那么有没有办法实现这一点而无需诉诸LINQ对象?

下面是一些演示我的问题的代码(它使用的是工厂创建的通用存储库类).

public interface INamedEntity
{
    int ID { get; set; }
    string Name { get; set; }
}

// This is an Entity Framework class which has CustomerID and CustomerName properties.
public partial class Customer: INamedEntity
{
    int INamedEntity.ID
    {
        get { return this.CustomerID; }
        set { this.CustomerID = value; }
    }
    string INamedEntity.Name
    {
        get { return this.CustomerName; }
        set { this.CustomerName = value; }
    }
}

...

public string GetName<T>(int entityID) where T: EntityObject, INamedEntity
{
    using(var repository = RepositoryFactory.CreateRepository<T>())
    {
        return repository
            .Where(e => e.ID == entityID)
            .Select(e.Name)
            .Single();
    }
}
Run Code Online (Sandbox Code Playgroud)

Lad*_*nka 5

这不受支持.您的Linq-to-entities查询只能使用实体的映射属性.如果使用接口属性,EF不知道如何将它们转换为SQL,因为它无法分析属性实现中的代码.

不要为实体使用接口 - EF根本不支持它.在您的特殊情况下,它甚至不能与任何其他ORM一起使用,因为您正在查询未知映射的属性.这将要求您构建自己的Linq提供程序,将查询转换为使用实际映射属性进行查询.


Eba*_*ood 0

在基于通用源并在 where 子句中使用接口成员的查询执行期间,会发生以下异常。

NotSupportedException:不支持接口成员 [InterfaceName].[MemberName] 的映射。

仅当查询应返回多个项目并且我使用 == 运算符时,才会发生异常。当使用 First、FirstOrDefault 或 Single 执行查询时,或者在 where 子句中使用 equals 或其他运算符时,我无法重现该错误。

参考:不支持接口