简体   繁体   中英

How to dynamically select the DbSet column name?

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;
}

In this link ( https://www.strathweb.com/2018/01/easy-way-to-create-ac-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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM