Search code examples
c#databaseentity-frameworkdbcontextdbset

Change DbSet with table name


I would like to know how to change DbSet on a DbContext using a table name (instead of using a fix DbSet as in the example). I've tried this solution but with no results.

        var type = Assembly.GetExecutingAssembly()
            .GetTypes()
            .FirstOrDefault(t => t.Name == tablename);

        DbSet dsContext = DbContext.Set(type);

        var data = DbContext.dsContext 
            .Where(r => r.C_NUMERICID == idLinea)
            .Where(r => r.C_TIMESTAMP > startDate)
            .OrderBy(r => r.C_TIMESTAMP)
            .ToList();

DbContext does not contain the defintion of 'dsContext'


Solution

  • I was querying wrong. This is the working solution.

    type = Assembly.GetExecutingAssembly()
       .GetTypes()
       .FirstOrDefault(t => t.Name == kepwareTableName);
    IQueryable data = DbContext.Set(type)
       .Where($"C_NUMERICID == {idLinea}")
       .Where("C_TIMESTAMP > @0", startDate)
       .OrderBy("C_TIMESTAMP");
    return data ;