SqlException是未处理的错误C#

时间:2016-02-05 11:20:15

标签: c# sql database

我是新手,并试图学习如何在C#中实现数据库的代码优先方法。我跟着this guide of Microsoft,但我的代码无法运行。 试图在互联网上修复一整天,但无法找到我的案例的任何解决方案。我继续前进,我迫切需要你的帮助。

您可以在教程中找到代码,但为方便起见,您也可以在下面找到它。

它停留在 db.Blogs.Add(blog)行,它出现以下错误:

  

SqlException未处理。附加信息       附加信息:建立与SQL Server的连接时发生与网络相关或特定于实例的错误。该   服务器未找到或无法访问。验证该实例   名称是正确的,并且SQL Server配置为允许远程   连接。 (提供者:SQL网络接口,错误:26 - 错误   找到指定的服务器/实例)

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
namespace CodeFirstNewDatabaseSample
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var db = new BloggingContext())
            {
                // Create and save a new Blog 
                Console.Write("Enter a name for a new Blog: ");
                var name = Console.ReadLine();

                var blog = new Blog { Name = name };
                db.Blogs.Add(blog);
                db.SaveChanges();

                // Display all Blogs from the database 
                var query = from b in db.Blogs
                            orderby b.Name
                            select b;

                Console.WriteLine("All blogs in the database:");
                foreach (var item in query)
                {
                    Console.WriteLine(item.Name);
                }

                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
            }
        }
    }

    public class Blog
    {
        public int BlogId { get; set; }
        public string Name { get; set; }

        public virtual List<Post> Posts { get; set; }
    }

    public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }

        public int BlogId { get; set; }
        public virtual Blog Blog { get; set; }
    }

    public class BloggingContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }
    }
}

以下是Server Explorer的情况:

enter image description here

以下是SQl服务器对象资源管理器的情况。

enter image description here

以下是建议后的app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="BloggingContextDb" connectionString="Data Source=|DataDirectory|BloggingContext.sdf" providerName="System.Data.SqlServerCe.4.0"/>
  </connectionStrings>
</configuration>

2 个答案:

答案 0 :(得分:2)

在这种情况下,DbContext将尝试为您创建数据库。如果在本地安装(默认使用VS2010),则在SQLExpress中;如果在本地安装(在默认情况下使用VS2012),则在LocalDb中安装。

您可以使用Visual Studio中的“服务器资源管理器”窗口查找本地安装的SQL Server实例。我怀疑没有本地安装,或者代码由于某种原因无法访问它(身份验证,授权等)。

这是我在使用SQL Server Server对象资源管理器窗口时在VS2013中看到的内容。从您的第二个屏幕截图看,您确实安装了LocalDb。你可以手动连接吗?

您可能需要specify an explicit connection string that DbContext can use。这通常在app.config中完成 - 请参阅创建app.config文件的链接。

enter image description here

答案 1 :(得分:2)

我不知道你是怎么结束那个app.config的 该配置无效供EntityFramework使用(据我所知),并使用位于项目文件夹下的BIN \ DEBUG文件夹中的SDF文件。
顺便说一句,SDF文件是 Sql Server Compact Edition 使用的文件,而不是 Sql Server Express Sql Server LocalDb

我已经按照相同的教程(仅使用Visual Studio 2015)而在我的项目中生成的app.config就是这个

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

唯一的问题(对我而言)是他们谈论配置Server Explorer以查看数据库文件的部分。我必须使用(localdb)\mssqllocaldb作为服务器名称而不是建议的(localdb)\v11.0
(查看app.config中上面的Parameter键)

现在,在本教程的第4步,我运行程序,一切都按预期工作。

所以我认为你应该用上面的内容改变app.config的内容,或者从头开始重复教程,注意不要改变任何东西。如果错误仍然存​​在,我只能建议切换到Visual Studio 2015社区版(它是免费的)