【问题标题】:Use variable name to query table in linq在linq中使用变量名查询表
【发布时间】:2018-04-25 09:51:01
【问题描述】:

我想知道是否可以通过在 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;
    }

【问题讨论】:

  • i want to be able to use this to write a linq query? LInq 仅指列表和表,而不是数据库本身的表名。
  • 仅仅因为您希望某些东西是可变的,并不一定意味着您需要使用string 来做到这一点。您是否愿意接受使源表变量而不使用字符串的解决方案?
  • @flater 是的,我对其他解决方案持开放态度,这是我设想的方式,但它不起作用,

标签: c# entity-framework linq


【解决方案1】:

你在这里:Scott shows you how to use 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; }
}

Generate Dynamic Linq query using outerIt

【讨论】:

  • 只包含外部链接的答案不是好的答案。链接可以弃用。将相关信息直接添加到您的答案中,以避免将来出现质量问题。
  • 我刚刚更新了我的答案。感谢您的重播
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-19
  • 1970-01-01
  • 2017-02-13
相关资源
最近更新 更多