How to dynamically select the DbSet column name?

.net-core ado.net c# entity-framework-core

Question

I have the following DbContext and entity (.Net core 3.11 console program).

public partial class MyDbContext : DbContext
{
    private readonly string _connectionString;

    public MyDbContext(string connectionString) => _connectionString = connectionString;

    public DbSet<MyEntity1> MyEntity1 { get; set; }
    public DbSet<MyEntityX> MyEntityX { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) =>
        optionsBuilder.UseSqlServer(_connectionString);
}

public class MyEntity1 { .... }
public class MyEntityX { .... }

I want to create a generic function with two type parameters for the entity class and column data type, and a string parameter for column name. The function will return

List<TColumn> F<TEntity, TColumn>(string colName)
{
    var list = dbContext.Set<TEntity>()
               .Select(x => x."colName?") // need to dynamic select the value of column
               .ToList();
    return list;
}
1
0
3/16/2020 5:44:25 PM

Accepted Answer

In this link (https://www.strathweb.com/2018/01/easy-way-to-create-a-c-lambda-expression-from-a-string-with-roslyn/), you can see how to create lambda expression from string. In there, he uses an example in Where(), but you should be able to create a Select() expression such as

var selectString = "x => x.colName";
var options = ScriptOptions.Default.AddReferences(typeof(TEntity).Assembly);

Func<TEntity, bool> selectExpression = await CSharpScript.EvaluateAsync<Func<TEntity, bool>>(selectString, options);

var selectedData = dbContext.Set<TEntity>().Select(selectExpression);

NOTE: you must always remember to use options to AddReferences() to your type.

1
3/16/2020 6:35:21 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow