实体框架内联SQL动态选择表名 [英] Entity Framework inline SQL dynamically select table name
问题描述
我不能改变数据库结构,记住这一点,
我会喜欢创建一个方法,我简单地传递表名和一个字段名称,并且我得到一个字符串列表,我可以用它来加载一个下拉列表。 (我正在使用实体框架6.x)
但是我正在绘制一个空白。任何帮助或指针都将不胜感激。
提前感谢
带EF的SQL查询字符串。只要告诉你你的退货类型:
私人名单< string> getFieldFromTable(string tableName,string fieldName)
{
using(var db = new Context())
{
var strings = db.Database.SqlQuery< string>(string。格式(SELECT {0} FROM {1},tableName,fieldName))ToList();
返回字符串;
}
}
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...
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;
}
}
这篇关于实体框架内联SQL动态选择表名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!