用于从不同表中获取记录的通用查询 [英] Generic query to get records from different tables

查看:59
本文介绍了用于从不同表中获取记录的通用查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的项目中,我们使用Linq-to-Entities连接到数据库。要读取有效记录,比方说,table1有方法:

In our project we connecting to database with Linq-to-Entities. To read valid records from ,let's say, table1 there is method:

public List<tableName> GetTableNameRecords()
{
    try
    {
        return (from x in _context.tableName
                          where x.valid == 1
                          select x).ToList();
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
}





它有效,但有问题 - 我们需要为每个表编写相同的查询,只更改表名。有没有办法编写通用方法,我们只能传递表名?类似于:





It works, but there is a problem - for each table we need to write the same query and only change table name. Is there a way to write generic method where we could only pass table name? Something like:

public List<T> GetRecords<T>()
{
    try
    {
        return (from x in _context.<T>
                          where x.valid == 1
                          select x).ToList();
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
}

推荐答案

You can use reflection for this, but you're facing some rather ugly code. However, if you're willing to change your models a little bit, you can do that in a relatively straightforward way.

Create an interface that has one property - valid, like so:







interface IValid
{
    bool valid { get; set; }
}










Make sure all your models that have this valid field implement the interface. Then you can do something like this:







List<T> GetValid<T>(DbContext context) where T: IValid
{
    return context.Set<T>().Where(x=>x.valid).ToList()
}










By having your models implement the interface, you can use an ordinary LINQ expression and have the compiler sort everything out


这篇关于用于从不同表中获取记录的通用查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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