我正在尝试学习C#ASP.NET MVC 5.我正在尝试使用Entity Framework来完成我所做的一切。
但是,我需要运行原始SQL查询并将结果返回到数组中。
这是我到目前为止所做的。
我创建了上下文类,它允许我连接到服务器,它还允许我在运行时更改数据库。
这是我的上下文类
using ScripterEngine.Models;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Core.EntityClient;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace ScripterEngine.DataAccessLayer
{
public class BaseContext : DbContext
{
protected string connectionName;
public DbSet<Campaign> Campaign { get; set; }
/**
* Created the connection to the server using the giving connection string name
*
* @param connName
*/
public BaseContext(string connName = "BaseConnection")
: base(connName)
{
connectionName = connName;
}
/**
* Changes the default database
*
* @param databaseName
*/
public BaseContext setDatabase(string databaseName)
{
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
//change the database before creating the new connection
builder.InitialCatalog = databaseName;
string sqlConnectionString = builder.ConnectionString;
return new BaseContext(sqlConnectionString);
}
}
}
如何在这里建立连接是我的工作
BaseContext db1 = new BaseContext("server1");
var db1New = db1.setDatabase("someTableName");
string tableName = "SomeTableName";
var results = db1New.Database.SqlQuery("SELECT LOWER(column_name) AS column_name FROM information_schema.columns WHERE table_name = @tableName", tableName).ToArray();
这会抛出错误
无法从用法推断出方法'System.Data.Entity.Database.SqlQuery(string,params object [])'的类型参数。尝试显式指定类型参数。 C:.NET Projects \ ScripterEngine \ ScripterEngine \ Controllers \ CampaignController.cs 42 27 ScripterEngine
如何执行此原始查询?
答案 0 :(得分:45)
指定string
作为类型参数。
var results = db1New.Database.SqlQuery<string>("SELECT LOWER(column_name) AS column_name FROM information_schema.columns WHERE table_name = @p0", tableName).ToArray();
^^^^^^