简体   繁体   English

实体框架中的通用查询方法

[英]Generic query method in Entity Framework

In my DB I have tables who have an attribute int DeleteState . 在我的数据库中,我有一些表,它们的属性为int DeleteState I want a generic method to query those tables. 我想要查询这些表的通用方法。 In other words a method who does this: Context.Table.Where(x => x.DeleteState == 0) . 换句话说,执行此操作的方法为: Context.Table.Where(x => x.DeleteState == 0)

I thought I could do this: 我以为我可以这样做:

public static class Extensions
{
  public static IQueryable<T> Exists<T>(this IQueryable<T> qry) where T : IDeletable
  {
    return qry.Where(x => x.DeleteState == 0);
  }
}

Where IDeletable is this: IDeletableIDeletable地方:

public interface IDeletable
{
    int DeleteState { get; set; }
}

Now I only have to add the IDeletable in the EF model: 现在,我只需要在EF模型中添加IDeletable

public partial class Table : EntityObject, IDeletable { ... }

I did this with the templating mechanism. 我是通过模板机制完成的。

Unfortunately, it doesn't work :( It compiles fine, but throws at runtime: 不幸的是,它不起作用:(它可以很好地编译,但是会在运行时抛出:

Unable to cast the type 'Table' to type 'IDeletable'. LINQ to Entities only supports casting Entity Data Model primitive types

if I call it like that: 如果我这样称呼它:

Context.Table.Exists();

How can I solve this problem? 我怎么解决这个问题? Could you think of a fix or a different method to achieve similar results? 您能想到一种修复或其他方法来获得相似的结果吗? Thx 谢谢

The problem you have is that the Entity Framework can only work with an Expression Tree. 您遇到的问题是,实体框架只能与表达式树一起使用。 Your function executes a query directly instead of building an Expression Tree. 您的函数直接执行查询,而不是构建表达式树。

A simpler solution would be to add a Model Defined Function . 一个更简单的解决方案是添加模型定义函数

A model defined function can be called directly on an instance of your context. 可以在上下文的实例上直接调用模型定义的函数。

Have you tried converting your objects to IDeletable before you actually query? 在实际查询之前,您是否尝试过将对象转换为IDeletable eg 例如

public static IQueryable<T> Exists<T>(this IQueryable<T> qry)
{     
    return qry.Select<T, IDeletable>(x => x).Where(x => x.DeleteState == 0).Cast<T>();
}

I haven't tested this code, however, the error rings a bell and I remember I had to do something similar. 我尚未测试此代码,但是,错误提示,我记得我必须做类似的事情。

Maybe: 也许:

public static IQueryable<T> Exists<T>(this IQueryable<T> qry)
{
    return qry.Where(x => (!typeof(IDeletable).IsAssignableFrom(x.GetType()) || typeof(IDeletable).IsAssignableFrom(x.GetType()) && ((IDeletable)x).DeleteState == 0));
}

Tsss, this is the answer: Linq Entity Framework generic filter method Tsss,这就是答案: Linq Entity Framework通用过滤方法

I forgot about the class here: 我在这里忘了class

... where T : class , IDeletable ...其中T: class ,IDeletable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM