在DbContext.Set()上的LINQ [英] LINQ On DbContext.Set()

查看:328
本文介绍了在DbContext.Set()上的LINQ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,基本上,我正在尝试从实体名称(字符串)返回DbSet.这是我所走的路:

So, basically I am trying to get a DbSet returned from entity name (string). This is how far I have gotten:

var customers = db.Set(Type.GetType("App.Model.Customer, 
                                     App.Model, 
                                     Version=1.0.0.0, 
                                     Culture=neutral, 
                                     PublicKeyToken=null"));

但是我不能执行其他,如Any()Single().为什么会这样,我该如何更改呢?

But then I cannot perform other LINQ like Any() or Single(). Why is that and how can I change it to do so?

推荐答案

DbSet .此类实现的接口之一是IQueryable,这也是非通用的.这就是为什么它不能用作对通用类型IQueryable<T>定义的所有这些LINQ扩展方法的输入的原因.

The non-generic overload of DbContext.Set returns an equally non-generic DbSet. One of the interfaces this class implements is IQueryable, again, non generic. That's the reason why it can't serve as input to any of these LINQ extension method that are defined on the generic type IQueryable<T>.

因此,实际上,如果您仍要使用LINQ,则仅推迟必须转换为通用IQueryable的时间.您可以做...

So in fact, if you still want to use LINQ, you only postpone the moment when you have to convert to a generic IQueryable. You could do...

var customers = db.Set(Type.GetType(...)).Cast<Customer>().Where(c => ...)

...但是,当然,您失去了在运行时动态定义类型的全部要点.

...but then of course you lose the whole point of defining the type dynamically, at runtime.

一旦动态启动,就必须动态继续.一种方法是在您的项目中添加 System.Linq.Dynamic . 然后,您可以编写类似...的查询

Once you start dynamically, you have to continue dynamically. One way to do that is by adding System.Linq.Dynamic to your project. Then you can write queries like...

var customers = db.Set(Type.GetType(...)).Where("CustomerId = @0", 1);

...这将返回具有CustomerId == 1Customer(包装在IQueryable<Customer>中).

...which will return you the Customer (wrapped in an IQueryable<Customer>) having CustomerId == 1.

您甚至可以使用Find方法:

var customer = db.Set(Type.GetType(...)).Find(1);

这将返回一个Customer实例.

这篇关于在DbContext.Set()上的LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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