0

If I use:

private List<string> GetDataFrom()
{
    var result = new List<string>();
    using (var context = new mainEntities())
    {
        var matches = context.data.Where(s => s.Width == 500).ToList();
        result.AddRange(matches.Select(t => t.Key));
    }
    return result;
}

It is giving me perfect results, but I want to use a method where I can use column name and value, like this:

private List<string> GetDataFrom(string columnName, int valToMatch)
{
    var result = new List<string>();
    using (var context = new mainEntities())
    {
        var propertyInfo = typeof(data).GetProperty(columnName).Name;
        var matches = context.data
                             .Where(p => p.propertyInfo == valToMatch);
        result.AddRange(matches.Select(t => t.Key));
    }
    return result;
}

This Method obviously doesn't work, so how can I do the same? I am using SqlLite, so some answers given do not apply. The whole problem is using propertyInfo the wrong way.

I tried various different approaches but no success.

This question is not a duplicate, because the suggested questions and their answers do not help much. I like this question to be reopened. I have found an answer myself I like to share.

YakovL
  • 6,451
  • 11
  • 52
  • 82
GrooverFromHolland
  • 828
  • 1
  • 14
  • 16
  • You cannot make column names variable in this way, for the same reason you cannot write `SELECT * FROM @tablenameparam WHERE @columnnameparam = @valueparam` in normal sql – Caius Jard Nov 02 '18 at 12:34
  • Im not following why you do it this way, what kind of model of entity are you using? How i would approach it is to look into the table the value i want (the name would be the column and the value well the value you are trying to get) – nalnpir Nov 02 '18 at 12:35

2 Answers2

0

ToString() method can not be translated into relevant SQL.

Try to use SqlFunctions.StringConvert(valToMatch) instead of valToMatch.ToString()

Dmitry Stepanov
  • 2,588
  • 6
  • 25
  • 42
-1
.ToString()

Doesn't works inside the Linq Query.

Inststed of .ToString() Function Use the following

SqlFunctions.StringConvert()

SEE THE FOLLOWING ANSWER https://stackoverflow.com/a/3292773/3736442

Meer
  • 2,627
  • 2
  • 18
  • 28