SpectrumContext是web.config中定义的连接。我不确定为什么这不加载。
我的字符串变量“results”引发以下错误:
类型'System.Web.Routing.RouteCollection + IgnoreRouteInternal'和 类型 'System.Web.Mvc.RouteCollectionExtensions + IgnoreRouteInternal' 具有相同的简单名称'IgnoreRouteInternal',因此不能 用于同一型号。给定模型中的所有类型必须具有唯一性 简单的名字。使用'NotMappedAttribute'或在代码中调用Ignore 第一个流畅的API,用于明确地从中排除属性或类型 模型。
HomeController.cs
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.Mvc;
using WebApplication1.Controllers;
using WebApplication1.DataAccessLayer;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
BaseContext db1 = new BaseContext("SpectrumContext");
string sql = "select description from dbo.workcategory where workcategoryid = 3";
string results = db1.Database.SqlQuery<string>(sql).First();
return View(results);
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
BaseContext.cs
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;
`test`using WebApplication1.Controllers;
namespace WebApplication1.DataAccessLayer
{
public class BaseContext : DbContext
{
protected string connectionName;
public DbSet<HomeController> description { get; set; }
/**
* Created the connection to the server using the giving connection string name
*
* @param connName
*/
public BaseContext(string connName = "SpectrumContext")
: 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);
}
}
}
Index.cshtml
@{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>ASP.NET</h1>
</div>
<div>
</div>
答案 0 :(得分:0)
为了帮助您入门,如果您只想执行简单的SQL语句,请立即抛弃(EF)DbContext
,直到您了解EF的工作原理及其用途。
在学习的过程中,您可以使用原始ADO执行简单的SQL语句,如下所示:
const string sql = "select description from dbo.workcategory where workcategoryid = 3";
var connectionString = ConfigurationManager.ConnectionStrings["SpectrumContext"].ConnectionString;
using (var cn = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(sql, cn))
{
var results = Convert.ToString(cmd.ExecuteScalar());
return View(results);
}
}