以编程方式在实体框架中使用包管理器控制台“Update-Database”等连接字符串

时间:2015-01-22 10:20:11

标签: c# entity-framework entity-framework-6 sqlconnection

我遇到了实体框架,编程连接字符串和包控制台管理器Update-DatabaseAdd-Migration等问题。

我在项目中使用configuration.xml文件,以便用户可以根据需要更改配置。

问题是以编程方式连接字符串......

如果我尝试使用Update-Database命令,我得到了这样的结果。

PM> Update-Database -Verbose
Using StartUp project 'acme'.
Using NuGet project 'acme'.
Target database: 'acme.Models.DbContext' (DataSource: .\SQLEXPRESS, Provider: System.Data.SqlClient, Origin: Convention).
Using Migrationens: [..., ..., ..., ..., ...].
Appending migration: ....

问题是,DataSource不是.\SQLEXPRESS。例如,My-SQLServer

连接字符串是。

Data Source=My-SQLServer\TS;initial catalog=acme;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework

原始的,有效的配置条目就是这个。

<connectionStrings>
  <!--<add name="DbContext" connectionString="Data Source=My-SQLServer\TS;initial catalog=acme;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework" providerName="System.Data.SqlClient" />-->
</connectionStrings>

DbContext是......

using System;
using System.Data;
using System.Data.Entity.Core.Objects;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Data.Entity.Core.EntityClient;
using System.Data.Common;
using System.Data.SqlClient;

namespace acme.Models
{
    public class DbContext : DbContext, IDbContextFactory<DbContext>
    {
        public DbContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
            Database.SetInitializer<DbContext>(new MigrateDatabaseToLatestVersion<DbContext, acme.Migrations.Configuration>());
        }

        public DbContext()
            : base()
        {
            Database.SetInitializer<DbContext>(new MigrateDatabaseToLatestVersion<DbContext, acme.Migrations.Configuration>());
        }

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

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>().Map(m => m.MapInheritedProperties());

            base.OnModelCreating(modelBuilder);
        }

        public DbContext Create()
        {
            /* First try (not working) */
            EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder();
            //ecsb.ProviderConnectionString = acme.ConfigFile.GetValue("ConnectionString");
            ecsb.Provider = "System.Data.SqlClient";
            ecsb.ProviderConnectionString = @"application name=";

            /* Second try https://msdn.microsoft.com/en-us/library/bb738533%28v=vs.110%29.aspx (not working) */
            // Initialize the connection string builder for the
            // underlying provider.
            SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();

            // Set the properties for the data source.
            sqlBuilder.DataSource = @"My-SQLServer\TS";
            sqlBuilder.InitialCatalog = "acme";
            sqlBuilder.IntegratedSecurity = true;
            sqlBuilder.MultipleActiveResultSets = true;
            sqlBuilder.ApplicationName = "EntityFramework";

            // Build the SqlConnection connection string.
            string providerString = sqlBuilder.ToString();

            // Initialize the EntityConnectionStringBuilder.
            EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();

            //Set the provider name.
            entityBuilder.Provider = "System.Data.SqlClient";

            // Set the provider-specific connection string.
            entityBuilder.ProviderConnectionString = providerString;

            return new DbContext(entityBuilder.ToString());
        }
    }
}

我希望你能帮助我:)。

提前致谢!

1 个答案:

答案 0 :(得分:1)

我知道这是一个老问题。但我遇到了同样的问题。

我的代码曾经工作过,但现在突然之间却没有。我确实将我的数据库移动到新服务器,但不是100%导致它的原因。无论哪种方式,我的App.Config和我的主网站的Web.Config都指向正确的连接字符串。不知道为什么忽略它们并使用。\ SQLEXPRESS ...

无论如何,我确实设法通过以下方式强制它使用正确的连接字符串(临时解决方案):

Add-Migration -ConnectionString "<connection string here>"
Update-Database -ConnectionString "<connection string here>"

它会询问提供商名称,在我的情况下是System.Data.SqlClient