EntityFramework忽略connectionString中的登录名

时间:2014-04-10 12:48:18

标签: c# entity-framework connection-string

嗨,我试图用EF配置我的第一个应用程序,但找不到连接到DB的方法

这是我的背景

public partial class FunzionamentoContext : DbContext
{
    public FunzionamentoContext()
        : base("FunzionamentoContext")
    {}

    static FunzionamentoContext()
    {
        Database.SetInitializer<FunzionamentoContext>(null);
    }

    public DbSet<Controllo> Controllo { get; set; }
}

这是连接字符串(存在于DAL项目的app.config文件中,因为我还没有UI项目):

<?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>
  <connectionStrings>
    <add name="FunzionamentoContext"
            providerName="System.Data.SqlClient"
            connectionString="Data Source=xyzxyz; Initial Catalog=dbName;
        Integrated Security=false;User ID=test;Password=test" />
  </connectionStrings>

  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

这是我测试连接的简单方法(仅在连接完成时进行搜索,接下来我将以更美的方式重写它:D)

    [Test]
    public void TestTrue()
    {
        FunzionamentoContext fctx = new FunzionamentoContext();
        Controllo c = new Controllo();
        .id = 1
        fctx.Controllo.Add((Controllo)c);
        fctx.SaveChanges(); 
    }

当我尝试连接时,我看到了这个错误:

FunzIA.UnitTest.DAL.TestFixture1.TestTrue: System.Data.Entity.Core.EntityException:基础提供程序在Open上失败。   ----&GT; System.Data.SqlClient.SqlException:无法打开数据库&#34; FunzionamentoContext&#34;登录请求。登录失败。 用户&#39; DOMAIN \ U123456&#39;。

登录失败

其中DOMAIN \ U123456是我的Windows帐户

为什么EF使用我的Windows帐户而不是连接字符串中写的那个?

1 个答案:

答案 0 :(得分:2)

我假设您将DAL放在与您实际运行的项目不同的项目中。

您的应用程序将使用您尝试运行的项目中的配置文件,而不是与DAL项目直接相关的项目。

我的意思是,如果您只使用测试项目(假设它与DAL位于不同的项目中),那么您需要测试项目的app.config中的连接字符串