简体   繁体   English

在实体框架中的动态 dbset 中使用 where 子句

[英]Use where clause in dynamic dbset in Entity Framework

Currently I am using the following code block to create DbSet dynamically and retrieve data from it -目前我正在使用以下代码块动态创建 DbSet 并从中检索数据 -

Type entityType = Type.GetType("MyProject.Models."+ EntityName + ", SkyTracker");
DbSet mySet = Db.Set(entityType);

foreach (var entity in mySet)
{

}

I would like to use a Where clause here ie .Where(m=>m.Id==1) or something like that.我想在这里使用 Where 子句,即.Where(m=>m.Id==1)或类似的东西。

Is there any way to do it ?有什么办法吗?

You should use generics here to make it simpler.您应该在此处使用泛型以使其更简单。

public DbSet<T> GetDbSet<T>() where T: class
{
    DbContext db = new DbContext("");
    return db.Set<T>();
}

public List<T> GetFilteredData<T>(Expression<Func<T, bool>> criteria) where T : class 
{
    DbContext db = new DbContext("");
    return db.Set<T>().Where(criteria).ToList();
}

And you can call these methods as following.您可以按如下方式调用这些方法。

Expression<Func<AudioClass, bool>> criteria = ac => ac.Name == "jazz";

var result = GetFilteredData(criteria);

Here AudioClass is just a sample class I created for example.例如,这里AudioClass只是我创建的一个示例类。

This should help you to implement the behavior you want to.这应该可以帮助您实现您想要的行为。

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

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