【发布时间】:2016-05-13 02:07:15
【问题描述】:
我正在尝试学习 C# ASP.NET MVC 5。我正在尝试将实体框架用于我所做的一切。
但是,我需要运行原始 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 项目\ScripterEngine\ScripterEngine\Controllers\CampaignController.cs 42 27 ScripterEngine
如何执行这个原始查询?
【问题讨论】:
标签: c# asp.net asp.net-mvc entity-framework asp.net-mvc-5