Dynamically select columns in runtime using entity framework

26,690

Solution 1

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.

Solution 2

You have to try with dynamic LINQ. Details are HERE

Share:
26,690
pravprab
Author by

pravprab

Imagine Imagine there's no countries It isn't hard to do Nothing to kill or die for And no religion too Imagine all the people Living life in peace... Imagine all the people Sharing all the world... You may say I'm a dreamer But I'm not the only one I hope someday you'll join us And the world will live as one John Lennon SOreadytohelp

Updated on July 30, 2022

Comments

  • pravprab
    pravprab almost 2 years

    I have an existing function like this

    public int sFunc(string sCol , int iId)
    {
        string sSqlQuery = "  select  " + sCol + " from TableName where ID = " +  iId ;
        // Executes query and returns value in column sCol
    }
    

    The table has four columns to store integer values and I am reading them separately using above function.

    Now I am converting it to Entity Framework .

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

    but the above function returns an error

    input string not in correct format

    because it returns the column name itself.

    I don't know how to solve this as I am very new to EF.

    Any help would be appreciated

    Thank you