C# · 12月 23, 2021

c# – 动态LINQ查询从数据库获取Field值

可能吗? Public String Get_Filed_By_Id(string table_Name,String Field_Name,string PK_val){ string strRes=””; using(mydbcontext db=new mydbcontext()) { var x=db.table_Name.Where(p=>p.Id=PK_val).FirstOrDefault().Field_Name; strRes=Convert.Tostring(x); } return strRes;}

要么

var x=(from o in db.table_Name where o.Id=PK_val select o.Field_Name).FirstOrDefault();

在这里,我传递Table_Name,Column_Name和Condition值(PK_val)以在特定条件(Id = Pk_val)内从Table_Name获取Column_Name.

可能吗??

解决方法

Is it possible??

是的.

首先,一些帮手:

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<IQueryable<object>,Expression<Func<object,object>>,IQueryable<object>>>((source,selector) => Queryable.Select(source,selector)); private static readonly MethodInfo Where = GetGenericMethodDeFinition< Func<IQueryable<object>,bool>>,object>>((source,predicate) => Queryable.Where(source,predicate)); private static readonly MethodInfo FirstOrDefault = GetGenericMethodDeFinition< Func<IQueryable<object>,object>>(source => Queryable.FirstOrDefault(source)); private static MethodInfo GetGenericMethodDeFinition<TDelegate>(Expression<TDelegate> e) { return ((MethodCallExpression)e.Body).Method.GetGenericMethodDeFinition(); } private static object Call(MethodInfo method,params object[] parameters) { return method.Invoke(null,parameters); } }}

现在你的功能:

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