首页 > 解决方案 > 在linq中使用变量名查询表

问题描述

我想知道是否可以通过在 linq 中使用变量来查询数据库集。

首先,我查询我的数据库以获取表名作为字符串,我想将其转换为表名:

    public static string getTableName()
    {
        string tableName = string.Empty;
        var department= "Sales";

        using (var context = new ALLDBEntities())
        {
            tableName = (from x in context.PROCESS_MATRIX
                where x.AREA.Equals(product)
                select x.ENTITY).FirstOrDefault();
        }

        return tableName;
    }

现在我将表名作为字符串,我希望能够使用它来编写 linq 查询,但alldbEntities.sales我不想使用 ,而是使用table. 这样做的原因是因为我需要编写多个查询来做同样的事情,因为我必须查询不同的表。

有没有办法做到这一点?

    public List<sales> GetData(DateTime startDate, DateTime endDate)
    {
        var table = getTableName();

        this.startDate = startDate.AddDays(-1);
        this.endDate = endDate.AddDays(1);

        using (var alldbEntities = new ALLDBEntities())
        {
            salesinfo = alldbEntities.sales.Where(f => f.Date >= this.startDate && f.Date <= this.endDate).ToList();
        }

        return salesinfo;
    }

标签: c#entity-frameworklinq

解决方案


你在这里:Scott 向你展示如何使用 Dynamic LINQ

你可以做的事情:

通过使用(导入)System.Linq.Dynamic 命名空间,动态表达式 API 被纳入范围。下面是将动态表达式 API 应用于 LINQ to SQL 数据源的示例。

var query =
    db.Customers.
    Where("City = @0 and Orders.Count >= @1", "London", 10).
    OrderBy("CompanyName").
    Select("new(CompanyName as Name, Phone)");

记得试试innerIt和outerIt

如何使用outerIt的一个例子

static void Main(string[] args)
{
    var claims = new List<Claim>();
    claims.Add(new Claim { Balance = 100, Tags = new List<string> { "Blah", "Blah Blah" } });
    claims.Add(new Claim { Balance = 500, Tags = new List<string> { "Dummy Tag", "Dummy tag 1" } });

    // tags to be searched for
    var tags = new List<string> { "New", "Blah" };
    var parameters = new List<object>();
    parameters.Add(tags);

    var query = claims.AsQueryable().Where("Tags.Any(@0.Contains(outerIt)) AND Balance > 100", parameters.ToArray());
}

public class Claim
{
    public decimal? Balance { get; set; }
    public List<string> Tags { get; set; }
}

使用 outerIt 生成动态 Linq 查询


推荐阅读