从不同的表中获取记录的通用查询

本文关键字:记录 查询 获取 | 更新日期: 2023-09-27 17:52:34

在我们的项目中,我们使用link -to- entities连接到数据库。要从表1中读取有效记录,可以使用方法:

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);
}
}

它工作,但有一个问题-对于每个表,我们需要编写相同的查询,只更改表名。是否有一种方法来写泛型方法,我们只能传递表名?比如:

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);
}
}

谢谢你的帮助

从不同的表中获取记录的通用查询

您可以为此使用反射,但是您将面临一些相当丑陋的代码。然而,如果你愿意稍微改变一下你的模型,你可以用一种相对直接的方式来做到这一点。

创建一个具有一个属性- valid的接口,如下所示:

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

确保所有具有此有效字段的模型都实现了该接口。然后你可以这样做:

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

通过让您的模型实现接口,您可以使用普通的LINQ表达式并让编译器对所有内容进行排序。

这是一个使用反射的扩展

    public static IEnumerable<T> GetRecords<T>(this IEnumerable<T> source)
    {
        //check property exists
        var temp = Activator.CreateInstance(typeof(T), new object[] { });
        if (temp.GetType().GetProperty("valid") == null)
            return source;
        return (from item in source
                let table = item.GetType()
                let property = table.GetProperty("valid")
                let value = property.GetValue(item, null)
                where (int)value == 1
                select item).ToList();
    }

用类似

的东西来命名它
 int count = _context.TableName.GetRecords().Count();