微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/csharp/91378.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐