实体框架代码首先导致数据库访问异常

时间:2015-10-27 20:01:47

标签: database sql-server-ce code-first entity-framework-6.1 mdf

最近开始尝试深入研究实体框架的代码第一种方法。我按照各种教程创建了一些数据库表,但没有一个能够解决问题。

从头开始大约3到4次,因为异常变得越来越荒谬。上次在第一次访问时创建了数据库,但由于缺少权限(使用集成安全性 - wat?),因此无法在第二个调试会话中连接到数据库。显然.mdf被系统进程阻止,只有在安全模式下重启才能让我摆脱它。

无论如何,重新开始。我有一个类库,它包含数据库模型和外部访问的网关类。我有一个Console项目来测试数据库的创建和访问。 EF通过NuGet安装在类库中,对EntityFramework.SqlServer.dll的引用被添加到Console项目中。

两个项目中的连接字符串都是这样的:

<connectionStrings>
    <add name="DbConnection"
        connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\LanguageCreator.mdf;Initial Catalog=LanguageCreator;Integrated Security=SSPI"
        providerName="System.Data.SqlClient" />
</connectionStrings>

我的上下文类看起来像这样:

public class LanguageContext : DbContext {
    public LanguageContext() : base("DbConnection") {
        // Have to set the DataDirectory in code because the wrong one gets set from the config.
        AppDomain.CurrentDomain.SetData("DataDirectory", Directory.GetCurrentDirectory());

        Database.SetInitializer(new CreateDatabaseIfNotExists<LanguageContext>());

        public DbSet<Language> Languages { get; set; }
        public DbSet< ... blablabla various other DbSets following, nothing of interest here.
    }

这就是我的网关的样子:

public class Gateway {
    public void InitializeDatabase() {
        using (LanguageContext context = new LanguageContext()) {
            context.Database.Initialize(true);

            // I did have a configuration class for migration, which seeds some initial data, which is why I'm trying to read the WordTypes here but I left that thing out this time ... will try to add it later on.
            IEnumerable<WordType> wordTypes = context.WordTypes.AsEnumerable();

            List<Language> languages = context.Languages.ToList();
        }
    }
}

电话看起来像这样:

class Program {
    static void Main(string[] args) {
        Gateway databaseGateway = new Gateway();

        databaseGateway.InitializeDatabase();
    }
}

现在,在没有任何特殊情况的情况下,我在启动调试会话时收到以下错误:

  

建立与SQL Server的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称是否正确,以及SQL Server是否配置为允许远程连接。 (提供程序:SQL网络接口,错误:50 - 发生本地数据库运行时错误。无法创建自动实例。请参阅Windows应用程序事件日志以获取错误详细信息。

不幸的是,Windows应用程序事件日志没有显示该错误的任何详细信息。或许我找到它太愚蠢......

实际导致此问题的原因是什么?如何解决此问题?我发现的一切都是关于访问外部SQL Server的,但我只是希望EF在本地创建一个.mdf并连接到它。

2 个答案:

答案 0 :(得分:0)

我对Entity Framework和数据库一般都很陌生,但我有一些建议可能有助于缩小问题的范围。

  1. “验证实例名称是否正确,以及SQL Server是否配置为允许远程连接。”通过使用其他程序连接服务器,查看服务器是否存在问题。如果您在EF之外连接它时遇到问题,可以将EF排除在外。

  2. 如果可以,请省略连接字符串或SQL数据库的任何提及,看看EF是否会为您生成LocalDB。 I believe this is the default behaviour of EF.如果这样做有效,我认为这也表明你的SQL服务器会给你带来麻烦。

  3. 同样,我对此非常陌生,所以只是想一想我会用我有限的知识来解决这个问题。希望它有用!

答案 1 :(得分:0)

好的,我偶然发现了。我在Console项目中通过NuGet安装了EntityFramework,并且在启动调试会话时,Visual Studio创建了.mdf。

由于在卸载EntityFramework后它仍然有效,我重新创建了项目并检查了差异。我发现app.config中的EntityFramework条目仍然存在,所以我将它们复制到新项目中,现在也可以了。

因此,如果您遇到同样的问题,请尝试在控制台项目的app.config中添加这些部分(或者您用于访问数据库类库的任何项目类型):

<configSections>
  <section name="entityFramework" 
           type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
           requirePermission="false" />
</configSections>
<connectionStrings>
  <add name="LanguageCreator.data.LanguageCreatorContext"
       connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\MyContext.mdf;Integrated Security=SSPI"
       providerName="System.Data.SqlClient" />
</connectionStrings>
<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>
相关问题