Dynamically select columns in runtime using entity framework

前端 未结 5 1253
旧巷少年郎
旧巷少年郎 2020-12-11 05:07

I have an existing function like this

public int sFunc(string sCol , int iId)
{
    string sSqlQuery = \"  select  \" + sCol + \" from TableName where ID = \         


        
相关标签:
5条回答
  • 2020-12-11 05:16

    Instead of passing the string column name as a parameter, try passing in a lambda expression, like:

    sFunc(x => x.FirstColumnName, rowId);
    sFunc(x => x.SecondColumnName, rowId);
    ...
    

    This will in the end give you intellisense for column names, so you avoid possible errors when column name is mistyped.

    More about this here: C# Pass Lambda Expression as Method Parameter

    However, if you must keep the same method signature, i.e. to support other/legacy code, then you can try this:

    public string sFunc(string sCol , int iId)
    {
        return TableRepository.Entities.Where(x => x.ID == iId).Select(x => (string) x.GetType().GetProperty(sCol).GetValue(x)});
    }
    

    You might need to adjust this a bit, I didn't have a quick way of testing this.

    0 讨论(0)
  • 2020-12-11 05:19

    This might help to solve your problem:

    public int sFunc(string sCol, int iId)
    {
        var _tableRepository = TableRepository.Entities.Where(x => x.ID == iId).Select(e => e).FirstOrDefault();
        if (_tableRepository == null) return 0;
    
        var _value = _tableRepository.GetType().GetProperties().Where(a => a.Name == sCol).Select(p => p.GetValue(_tableRepository, null)).FirstOrDefault();
    
        return _value != null ? Convert.ToInt32(_value.ToString()) : 0;
    }
    

    This method now work for dynamically input method parameter sCol.

    0 讨论(0)
  • 2020-12-11 05:20

    You could use Reflection, something like this (not tested code):

    public string sFunc(string sCol , int iId)
    {
      var row = TableRepository.Entities.Where(x => x.ID == iId);
      var type = typeof(row);
      var propInfo = type.GetProperty(sCol);
    
      if (propInfo != null)
      {
        string value = (string)propInfo.GetValue(row);
    
        return value;
      }
    
      return null;
    }
    
    0 讨论(0)
  • 2020-12-11 05:22

    You can do this:

            var entity = _dbContext.Find(YourEntity, entityKey);
            // Finds column to select or update
            PropertyInfo propertyInfo = entity.GetType().GetProperty("TheColumnVariable");
    
    0 讨论(0)
  • 2020-12-11 05:25

    You have to try with dynamic LINQ. Details are HERE

    0 讨论(0)
提交回复
热议问题