How to dynamically select the DbSet column name?

.net-core c# entity-framework-core


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) =>

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
    return list;
3/16/2020 5:44:25 PM

Accepted Answer

In this link (, 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.

3/16/2020 6:35:21 PM

Related Questions


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