0

I have a less than optimal database that I am querying which strangely, instead of storing look up items in a parent child relationship, stores them in individual tables. So, for example, there is a table for countries and one for states etc. I cannot change the database structure, keeping this in mind,

I would like to create a method where I simply pass in table name, and a field name, and I get a list of strings that I can use to load a dropdown. (I am using Entity Framework 6.x)

However I am drawing a blank. Any help or pointers would be much appreciated.

Thanks in advance...

1 Answer 1

3

You can use a SQL query string with EF. Just tell it your return type:

private List<string> getFieldFromTable(string tableName, string fieldName)
{
    using (var db = new Context())
    {
        var strings = db.Database.SqlQuery<string>(string.Format("SELECT {0} FROM {1}",tableName, fieldName)).ToList();
        return strings;
    }

}
Sign up to request clarification or add additional context in comments.

1 Comment

Be careful with this approach, since it could lead to a SQL injection attack.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.