我正在try 学习C#ASP.NETMVC5,并且我正在try 在我所做的一切中使用实体框架.
但是,我需要运行一个原始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();
这会抛出一个错误
方法"系统"的类型参数.数据实体数据库无法从用法推断SqlQuery(string,params object[]).try 显式指定类型参数.C:.NET项目\ScripteEngine\ScripteEngine\Controllers\ActivationController.cs 42 27脚本引擎
我如何执行这个原始查询?