entity-framework - 通过接口(interface)属性 LINQ to Entities

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

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

但是,当我尝试针对这些接口(interface)方法编写 LINQ to entity 查询时,我得到了 NotSupportedException,因为查询不是直接使用类的属性,而是通过接口(interface)。

我想把繁重的工作交给数据库层,那么有没有办法在不使用 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();
    }
}

最佳答案

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

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

关于entity-framework - 通过接口(interface)属性 LINQ to Entities,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9326462/

相关文章:

java - 允许单位使用设计模式在 Java 中攻击地面、空中或两者的能力的接口(interface)

git - 暂存具有特定扩展名的文件,并且只有那些在 git status 中显示为已修改的文件

git - heroku:src refspec master 不匹配任何

Android repo 命令和切换分支

c# - Entity Framework ——引入外键约束可能会造成循环

sql-server - 当 Integrated Security=false 时,CREATE DATABASE 权限在数据库 'master' 中被拒绝 - 为什么尝试创建已存在的数据库?

c# - 当无法找到请求的 PostgreSQL 表时,如何捕获异常并使用错误代码?

database - Entity Framework 枚举仅作为 POCO

php - 是否可以有一个具有私有(private)/ protected 方法的接口(interface)?

python - 为什么 pylint 一直说我的类(class)是 R0923 - 'interface not implemented'