LINQ to Entities通过接口属性

时间:2012-02-17 10:20:15

标签: entity-framework interface repository business-logic-layer

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

然而,当我尝试针对这些接口方法编写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();
    }
}

3 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:0)

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

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

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

参考:Interface not supported

答案 2 :(得分:0)

您可以使用动态查询库(http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx)。

        if (typeof (INamedEntity).IsAssignableFrom(typeof (T)))
        {
            q = q.Where("ID ==@0", id);
        }