Dynamic LINQ query to get Field value from Database

前端 未结 4 1277
耶瑟儿~
耶瑟儿~ 2021-01-18 03:20

is it possible?

Public String Get_Filed_By_Id(string table_Name,String Field_Name,string PK_val)
{
    string strRes=\"\";
    using(mydbcontext db=new mydbc         


        
4条回答
  •  旧时难觅i
    2021-01-18 03:58

    Is it possible??

    Yes, it is.

    First, some helpers:

    using System;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Reflection;
    
    namespace YourNamespace
    {
        internal static class DbHelpers
        {
            public static object GetColumnById(this object dbContext, string tableName, string columnName, object id)
            {
                var table = (IQueryable)dbContext.GetType().GetProperty(tableName).GetValue(dbContext, null);
                var row = Expression.Parameter(table.ElementType, "row");
                var filter = Expression.Lambda(Expression.Equal(Expression.Property(row, "Id"), Expression.Constant(id)), row);
                var column = Expression.Property(row, columnName);
                var selector = Expression.Lambda(column, row);
                var query = Call(Where.MakeGenericMethod(row.Type), table, filter);
                query = Call(Select.MakeGenericMethod(row.Type, column.Type), query, selector);
                var value = Call(FirstOrDefault.MakeGenericMethod(column.Type), query);
                return value;
            }
            private static readonly MethodInfo Select = GetGenericMethodDefinition<
                Func, Expression>, IQueryable>>((source, selector) =>
                Queryable.Select(source, selector));
            private static readonly MethodInfo Where = GetGenericMethodDefinition<
                Func, Expression>, object>>((source, predicate) =>
                Queryable.Where(source, predicate));
            private static readonly MethodInfo FirstOrDefault = GetGenericMethodDefinition<
                Func, object>>(source =>
                Queryable.FirstOrDefault(source));
            private static MethodInfo GetGenericMethodDefinition(Expression e)
            {
                return ((MethodCallExpression)e.Body).Method.GetGenericMethodDefinition();
            }
            private static object Call(MethodInfo method, params object[] parameters)
            {
                return method.Invoke(null, parameters);
            }
        }
    }
    
    
    

    and now your function:

    public string Get_Field_By_Id(string table_Name, string field_Name, string PK_val)
    {
        using (var db = new mydbcontext())
            return Convert.ToString(db.GetColumnById(table_Name, field_Name, PK_val));
    }
    

    提交回复
    热议问题