Entity framework - get entity by name

前端 未结 2 1208
悲&欢浪女
悲&欢浪女 2020-12-03 03:42

I have the following code (example):

public dynamic GetData(string name) 
{
    using(var ctx = GetObjectContext()) 
    {
        switch (name) 
        {
          


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 04:32

    You can use code like this

    private IEnumerable GetList(string connectionString, Func caster)
    {
        using (var ctx = new DbContext(connectionString))
        {
            var setMethod = ctx.GetType().GetMethod("Set").MakeGenericMethod(typeof(T));
    
            var querable = ((DbSet)setMethod
            .Invoke(this, null))
            .AsNoTracking()
            .AsQueryable();
    
            return querable
                .Select(x => caster(x))
                .ToList();
        }
    }
    
    
    

    To call like this:

    var branchList = GetList("connectionStringName", x => (Branch)x);
    

    You can remove .AsNoTracking() and remove .ToList(), then you will get pure IQueryable which you can query further.

    提交回复
    热议问题