加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用实体框架在运行时动态选择列

发布时间:2020-12-15 07:42:54 所属栏目:百科 来源:网络整理
导读:我有这样的现有功能 public int sFunc(string sCol,int iId){ string sSqlQuery = " select " + sCol + " from TableName where ID = " + iId ; // Executes query and returns value in column sCol} 该表有四列存储整数值,我使用上面的函数分别读取它们.
我有这样的现有功能
public int sFunc(string sCol,int iId)
{
    string sSqlQuery = "  select  " + sCol + " from TableName where ID = " +  iId ;
    // Executes query and returns value in column sCol
}

该表有四列存储整数值,我使用上面的函数分别读取它们.

现在我将它转换为Entity Framework.

public int sFunc(string sCol,int iId)
{
     return Convert.ToInt32(TableRepository.Entities.Where(x => x.ID == iId).Select(x => sCol ).FirstOrDefault());
}

但上面的函数返回错误

input string not in correct format

因为它返回列名本身.

我不知道如何解决这个问题,因为我对EF很新.

任何帮助,将不胜感激

谢谢

解决方法

这可能有助于解决您的问题:
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;
}

此方法现在适用于动态输入方法参数sCol.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读