简体   繁体   English

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

[英]Programmatically connection string in entity framework with package manager console “Update-Database” etc

i have a problem with the entity framework, the programmatically connection string and the package console manager Update-Database or Add-Migration etc. 我在实体框架,以编程方式连接的字符串以及程序包控制台管理器Update-DatabaseAdd-Migration等方面遇到问题。

I'm using a configuration.xml file for my project so that the users can change the configuration for their needs. 我正在为我的项目使用configuration.xml文件,以便用户可以根据需要更改配置。

The problem is the programmatically connection string... 问题是以编程方式连接字符串...

If I try to use the Update-Database command i got a result like this. 如果我尝试使用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: ....

The problem is, that the DataSource is not .\\SQLEXPRESS . 问题是,数据源不是.\\SQLEXPRESS It's My-SQLServer for example. 例如My-SQLServer

Connection string is. 连接字符串是。

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

And the original, working config entry is this. 原始的有效配置条目是这个。

<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>

The DbContext is... 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());
        }
    }
}

I hope you can help me :) 我希望你能帮帮我 :)

Thanks in Advance! 提前致谢!

I know this is an old question. 我知道这是一个老问题。 But I'm having the same issue. 但是我有同样的问题。

My code used to work, but now all of a sudden it doesn't. 我的代码曾经可以工作,但是现在突然不起作用了。 I did move my database to a new server, but not 100% what has caused it yet. 我确实将数据库移到了新服务器上,但是还没有100%造成它。 Either way, my App.Config, and my main website's Web.Config are both pointing to the correct connection string. 无论哪种方式,我的App.Config和主网站的Web.Config都都指向正确的连接字符串。 No idea why it's ignoring them and using .\\SQLEXPRESS... 不知道为什么它会忽略它们并使用。\\ SQLEXPRESS ...

Anyways, I did manage to force it use the correct connection string (temporary solution) by: 无论如何,我设法通过以下方式强制使用正确的连接字符串(临时解决方案):

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

It'll ask for provider name, in my case it was System.Data.SqlClient . 它会要求提供者名称,在我的情况下是System.Data.SqlClient

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

相关问题 实体框架核心 - “更新数据库”不起作用 - Entity Framework Core - 'Update-Database' not working 带有-ConnectionString的实体框架更新数据库 - Entity Framework Update-Database with -ConnectionString 实体框架6中“更新数据库”之后发生错误 - Error after 'update-database' in Entity Framework 6 如何从Visual Studio中的包管理器控制台调用针对SQL Azure的update-database? - How to call update-database from package manager console in Visual Studio against SQL Azure? 实体框架代码第一次更新 - 数据库在CREATE DATABASE上失败 - Entity Framework code first update-database fails on CREATE DATABASE 在Visual Studio中的程序包管理器控制台上执行“更新数据库”时,出现错误:找不到内容根文件夹 - When doing an “update-database” on the package manager console in visual studio i get error : Could not find content root folder Entity Framework Core 不在更新数据库上创建数据库 - Entity Framework Core not creating database on update-database 在实体框架6的更新数据库上未调用Seed方法 - Seed method is not called on update-database, Entity Framework 6 实体框架核心更新-数据库特定迁移 - Entity framework Core Update-database specific migration 在 Entity Framework Core 中使用 Update-Database 添加新列 - Adding new column using Update-Database in Entity Framework Core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM