我有一个SQL查询,我想使用EntityFramework和Linq调用此查询。我怎样才能做到这一点?
我想获取包含特定列名的表名:
SELECT DISTINCT t.name AS 'TableName'
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%CustomField%'
ORDER BY TableName
答案 0 :(得分:0)
我不确定你为什么会在实体中搜索那样的表。
Msdn充满了exemple
它的总和是:参数化查询返回ObjectQuery<string>
。
using (myEntities myContext = new myEntities())
{
// Create a query string
string myQuery = @"SELECT DISTINCT t.name AS 'TableName' "+
"FROM sys.columns c "+
"JOIN sys.tables t ON c.object_id = t.object_id "+
"WHERE c.name LIKE '%@CustomField%' "+
"ORDER BY TableName";
// Create a query
//If you return a primitive type you can use ObjectQuery<string>
ObjectQuery<DbDataRecord> tableQuery = new ObjectQuery<DbDataRecord>(myQuery, myContext);
// Add parameters.
tableQuery.Parameters.Add(new ObjectParameter("CustomField", "FOOBAR"));
// Go through the Result
foreach (DbDataRecord rec in tableQuery)
{
Console.WriteLine("TableName\t [{0}]", rec[0]);
}
}
答案 1 :(得分:0)
string Query = "SELECT DISTINCT t.name AS 'TableName' "+
"FROM sys.columns c "+
"JOIN sys.tables t ON c.object_id = t.object_id "+
"WHERE c.name LIKE '%@table%' "+
"ORDER BY TableName"
vr db = new DB();
string table = "YourTableName";
var result = db.Database.SqlQuery<string>(Query, new SqlParameter("@table", table)).ToList();