Entity Framework inline SQL dynamically select table name

社会主义新天地 提交于 2019-12-12 04:56:07

问题


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:


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;
    }

}


来源:https://stackoverflow.com/questions/28749203/entity-framework-inline-sql-dynamically-select-table-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!