简体   繁体   English

ASP.NET MVC无法从本地SQL Server Express数据库检索数据

[英]ASP.NET MVC unable to retrieve data from local SQL Server Express database

First of all please excuse me, but I am a total newbie when it comes to ASP.NET as I'm trying to learn some of it at the moment. 首先,请原谅,但是当我尝试学习其中的一些内容时,对于ASP.NET来说我是一个新手。

I am following one of online tutorials for ASP.NET MVC4, but am using Visual Studio 2015 Community (MVC5) and SQL Server 2014 Express. 我正在关注ASP.NET MVC4的在线教程之一,但是正在使用Visual Studio 2015社区(MVC5)和SQL Server 2014 Express。

The goal is to retrieve data from a local SQL Server Express database using Windows authentication. 目标是使用Windows身份验证从本地SQL Server Express数据库检索数据。 In this case, employees with their id, name, city and gender. 在这种情况下,请提供其ID,姓名,城市和性别的员工。 At this moment I get the following error: 这时出现以下错误:

An exception of type 'System.Data.Entity.Core.EntityException' occurred in EntityFramework.SqlServer.dll but was not handled in user code EntityFramework.SqlServer.dll中发生类型为'System.Data.Entity.Core.EntityException'的异常,但未在用户代码中处理

Additional information: The underlying provider failed on Open. 附加信息:基础提供程序在打开时失败。

The database looks like this - Ids as int , rest as varchar(50) : 数据库如下所示-Ids为int ,其余为varchar(50)

在此处输入图片说明

Employee.cs located in Model: Employee.cs位于模型中:

[Table("tblEmployee")]
public class Employee
{
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string City { get; set; }
}

EmployeeContext.cs : EmployeeContext.cs

public class EmployeeContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
}

EmployeeController.cs : EmployeeController.cs

public class EmployeeController : Controller
{
        // GET: Employee
        public ActionResult Details(int id)
        {
            EmployeeContext employeeContext = new EmployeeContext();
            Employee employee = employeeContext.Employees.Single(emp => emp.EmployeeId == id);
            return View(employee);
        }
}

The view - Details.cshtml : 视图-Details.cshtml

@model MVCDemo.Models.Employee

@{
    ViewBag.Title = "Employee Details";
}

<h2>Employee Details</h2>
<table style="font-family:Arial">
    <tr>
        <td>
            <b>Employee ID:</b>
        </td>
        <td>
            @Model.EmployeeId
        </td>
    </tr>
    <tr>
        <td>
            <b>Name:</b>
        </td>
        <td>
            @Model.Name
        </td>
    </tr>
    <tr>
        <td>
            <b>Gender:</b>
        </td>
        <td>
            @Model.Gender
        </td>
    </tr>
    <tr>
        <td>
            <b>City:</b>
        </td>
        <td>
            @Model.City
        </td>
    </tr>
</table>

And finally, the connection string from web.config in the root (I made sure) directory: 最后,来自根目录(我确定)中web.config的连接字符串:

<add name="EmployeeContext" 
     connectionString="Data Source=DESKTOP-6RQ94N9\MAIN;Initial Catalog=Sample;Integrated Security=SSPI"
     providerName="System.Data.SqlClient" />

The default connectionString="Data Source=.\\SQLEXPRESS; simply didn't work. Anyways, Server explorer shows a successful data connection to the database, I can browse the tables and their columns within the Visual Studio. 默认的connectionString="Data Source=.\\SQLEXPRESS;根本不起作用。无论如何,服务器浏览器显示了到数据库的成功数据连接,我可以在Visual Studio中浏览表及其列。

When I launch the project and try for example: 当我启动该项目并尝试例如:

http://localhost/MVCDemo/Employee/Details/1

The site just keeps loading for a while and then the above mentioned exception occurs at 该站点只是保持加载一段时间,然后上述异常发生在

Employee employee = employeeContext.Employees.Single(emp => emp.EmployeeId == id);

When I debug the application, employeeContext.Employees.Local.Count shows 0, so I guess there is no data being retrieved. 当我调试应用程序时, employeeContext.Employees.Local.Count显示为0,所以我猜没有数据被检索。

Thank you very much for help! 非常感谢您的帮助!

Well, see How to: Access SQL Server Using Windows Integrated Security for details if using that option. 好吧,有关使用该选项的详细信息,请参见如何:使用Windows集成安全性访问SQL Server

You're able to connect to SQL as "you" within Visual Studio (or SSMS) because you're running Visual Studio as "you" ( your Windows user account). 你可以连接到SQL为“你”中的Visual Studio(SSMS或),因为你在运行Visual Studio为“你”(Windows用户帐户)。 Your Asp.Net site isn't . 您的Asp.Net网站不是

You could use SQL Authentication (instead) so your application (ASP.Net) and data store (SQL) users are separate and therefore can be managed separately, not have to deal with (creation of) actual Windows users. 您可以(而不是)使用SQL身份验证,因此您的应用程序(ASP.Net)用户和数据存储(SQL)用户是分开的,因此可以单独管理,而不必处理(创建)实际的Windows用户。 This will be more apparent if/when you go to production/hosting (eg web server and sql server are separate, no Windows "domain", etc.). 如果/当您进入生产/托管时(例如,Web服务器和sql服务器是分开的,没有Windows“域”等),这将更加明显。

As for connectivity issues see How to Troubleshoot Connecting to the SQL Server Database Engine 至于连接问题,请参阅如何解决连接到SQL Server数据库引擎的问题。

Hth. Hth。

Are you sure that employeeContext.Employees.Local.Count even tries to call a database? 您确定employeeContext.Employees.Local.Count甚至尝试调用数据库吗? What you need is to check the name of your SQL Server Express instance. 您需要检查SQL Server Express实例的名称。 Go to your folder with Microsoft SQL Server (your version) in all programs in the Start Menu and click Sql Server Configuration Manager . 在“开始”菜单的所有程序中,转到包含Microsoft SQL Server (your version)文件夹,然后单击“ Sql Server Configuration Manager In SQL Server Services tab you will see SQL Server (NAME) , usually it shows SQL Server (SQLEXPRESS) if you did not change the name during the installation. SQL Server Services选项卡中,您将看到SQL Server (NAME) ,如果您在安装过程中未更改名称,通常会显示SQL Server (SQLEXPRESS)
在此处输入图片说明 Moreover, if you are able to access SQL Server from your Visual Studio with SQLEXPRESS name then you can easily access it from the ASP.NET website that you run locally. 此外,如果您能够使用SQLEXPRESS名称从Visual Studio访问SQL Server,则可以从本地运行的ASP.NET网站轻松访问它。 One of my projects has the following connection string: 我的一个项目具有以下连接字符串:

<add name="DatabaseContext" connectionString="Data Source=DESKTOP-111111N\SQLEXPRESS;Initial Catalog=Sample;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False" providerName="System.Data.SqlClient" />

And please try to make a call to your database like this: employeeContext.Employees.Count() . 并且请尝试像这样调用数据库: employeeContext.Employees.Count()
I hope that will help you! 希望对您有所帮助!

UPDATE 更新

Please also check what connection string is set in your Database Context class constructor, for my project it is base("DatabaseContext") : 另请检查在数据库上下文类构造函数中设置了什么连接字符串,对于我的项目,它是base("DatabaseContext")

public class DatabaseContext : DbContext
{
    public DatabaseContext()
        : base("DatabaseContext")
    {
    }

}


And for your project it will be base("EmployeeContext") . 对于您的项目,它将是base("EmployeeContext")

Well, in this case I've actually made a workaround by creating an user with SELECT permission and updated my connection string with login credentials. 好吧,在这种情况下,我实际上通过创建具有SELECT权限的用户并使用登录凭据更新了我的连接字符串来进行了变通。

After that, I've successfully retrieved the information I needed from the database. 之后,我已经成功地从数据库中检索了所需的信息。 Thank you all for your help! 谢谢大家的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM