动态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_NameColumn_Name和Condition值( PK_val )以在特定条件( Id=Pk_val )内从Table_Name获取Column_Name

可能吗??

可能吗??

是的。

首先,一些帮手:

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

现在你的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)); } 

实际上,EntityFramework实际上是不可能的(据我所知)。 如果您只需要字段名称,那么您可以使用@ Den提出的解决方案。 但是您也想将表名指定为参数。 所以我建议你使用标准的Sql Connector api,并使用你提供的参数构建查询字符串。

检查此链接是否使用标准sql连接器api。

我也有这个问题,我知道这不是你想要的,你需要编写更多的代码,但它比你想写的更干净。
使用存储库模式
对于每个表,您应该有一个模型类和Repository类。
考虑一下这段代码(这个代码来自我的一个项目)
这是我的评论表(这可以是带或不带导航属性的任何东西)

  public sealed class Comment { public string CommentText { get; set; } public DateTime PostDate { get; set; } public int PostId { get; set; } public int? PageId { get; set; } public Page Page { get; set; } public User User { get; set; } public string UserId { get; set; } public int? ParentId { get; set; } public Comment[] ChildComments { get; set; } } 

RepositoryComment

  public sealed class CommentRepository : BaseRepository { public CommentRepository(BabySitterContext context) : base(context) { } } 

以及使用表名(此处为模型)和字段发送查询的基类(可以扩展clas以获得更多function)

 public class BaseRepository where T : class { protected BabySitterContext Context; private readonly PluralizationService _pluralizer = PluralizationService.CreateService(CultureInfo.GetCultureInfo("en")); public BaseRepository(BabySitterContext context) { this.Context = context; } public bool Add(T t) { Context.Set().Add(t); Context.SaveChanges(); return true; } public bool Update(T t) { var entityName = GetEntityName(); object originalItem; var key = ((IObjectContextAdapter)Context).ObjectContext.CreateEntityKey(entityName, t); if (((IObjectContextAdapter)Context).ObjectContext.TryGetObjectByKey(key, out originalItem)) { ((IObjectContextAdapter)Context).ObjectContext.ApplyCurrentValues(key.EntitySetName, t); } Context.SaveChanges(); return true; } public void Attach(T t) { if (t == null) { throw new ArgumentNullException("t"); } Context.Set().Attach(t); Context.SaveChanges(); } public void Remove(T t) { if (t == null) { throw new ArgumentNullException("t"); } Context.Set().Remove(t); Context.SaveChanges(); } public IEnumerable Get(Expression> filter = null, Func, IOrderedQueryable> orderBy = null, string includeProperties = "") { IQueryable query = Context.Set(); if (filter != null) { query = query.Where(filter.Expand()); } foreach (var includeProperty in includeProperties.Split (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { query = query.Include(includeProperty); } if (orderBy != null) { return orderBy(query).ToList(); } else { return query.ToList(); } } private string GetEntityName() where TEntity : class { return string.Format("{0}.{1}", ((IObjectContextAdapter)Context).ObjectContext.DefaultContainerName, _pluralizer.Pluralize(typeof(TEntity).Name)); } public virtual IEnumerable GetByBusinessKey(T entity) { return null; } } 

对于任何其他表,只需创建模型类和reposiotry然后从基类inheritance

使用代码

  var context = new BabySitterContext(); var _commentRepository = new CommentRepository(context); var comment = _commentRepository.Get(x => x.PostId == id).FirstOrDefault(); 

不,但是这样

 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).Select(b=>b.Field_Name).FirstOrDefault(); strRes=Convert.Tostring(x); } return strRes; }