LINQ to Entities通过接口属性 [英] LINQ to Entities through Interface Property

查看:162
本文介绍了LINQ to Entities通过接口属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a situation where I would like to use a single business logic class to perform similar operations on a variety of entity framework classes. I have defined an interface which these classes implement in a partial class file.

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

However when I try to write a LINQ to entities query against these interface methods I get a NotSupportedException since the query is not using the class's properties directly but through an interface.

我想把繁重的工作保留到数据库层,所以有没有办法实现这一点求助LINQ到对象?

I would like to keep the heavy lifting to the database tier so is there a way to achieve this without resorting to LINQ to objects?

这里有一些代码可以演示我的问题(它使用工厂创建的通用存储库类)。

Here is some code which demonstrates my problem (it is using a generic repository class created by a factory).

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();
    }
}


推荐答案

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

This is not supported. Your Linq-to-entities query can use only mapped properties of your entities. If you use interface properties EF doesn't know how to convert them to SQL because it is not able to analyze your code in property implementation.

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

Don't use interfaces for entities - EF doesn't support it at all. In your special case it will even not work with any other ORM because you are querying on properties which are unknown to mapping. This would require you to build your own Linq provider translating your query to query with real mapped properties.

这篇关于LINQ to Entities通过接口属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆