简体   繁体   中英

Entity framework: Retrieving data with column name and value

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.

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

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

.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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM