String in expression Entity C#

Asked

Viewed 94 times

1

I need to make a dynamic query similar to the example below

String tabela = "NomeTabela";
Var x = db.("NomeTabela").ToList();

Something like this where the table name will change according to the need.

  • In which scenario does it need to happen?

  • The goal is to use something like Javascript Eval where I can mount a string and run as a method...

  • I see this with many problems, mainly because it will work with reflection ... I would abandon it ... not good, maybe it lacks context for us to indicate a better solution.

  • Let’s suppose that I save a database a series of expressions in string format... and I wanted to recover these expressions by running them one by one... example: line1: "var registros1 = 100", Linha2: "var registro2 = 200" and line3: "var total = registro1 + registro2"... Not that the sum is the goal.. where I could register a series of other codes or expressions....

1 answer

1


In your class DbContext create a method, for example, Set, that returns a DbSet from the name passed in parameter (from your table):

public DbSet Set(string name)
{
    // talvez seja necessário adicionar o namespace do seu contexto
    return base.Set(Type.GetType(name));
}

Who then manages to make a query thus:

using (var db = new YourDataContext())
{
    // Como o DbSet não é genérico, não pode utilizar o código assim:
    // db.Set("Namespace.EntityName").AsQueryable().Where(a=> a.HasSomeValue...
    // As suas queries devem também ser à base de strings
    // Precisa utilizar o package/namespace nuget "System.Linq.Dynamic"
    var results = db.Set("Namespace.EntityName").AsQueryable().Where("SomeProperty > @1 AND SomeThing < @2", aValue, anotherValue);
    // agora consegue iterar a coleção dos objetos resultante
}

Answer given in Soen: Dynamic table name in Linq

More information on System.Linq.Dynamic here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.