Hoan Tran
Hoan Tran

Reputation: 385

C# + MySql + Code First: Format of the initialization string does not conform to specification starting at index 0

I have created a Library Project to connect with MySQL DB.

  1. Including MySql.Data, MySql.Data.Entity.EF6 by Nuget => OK.
  2. Installed EntityFramework by Nuget => OK
  3. I created a MyContext.cs:
namespace Project_Core.DAL.Context
{
    [DbConfigurationType(typeof(MySqlEFConfiguration))]
    public class MyContext: DbContext
    {
        public MyContext()
            : base("myDbContext")
        {

        }

        public DbSet<Staff> Staffs { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }
}
  1. I edited the App.config:

<connectionStrings> <add name="myDbContext" providerName="MySql.Data.MySqlClient" connectionString="Data Source=localhost; port=3306; Initial Catalog=dbtest; uid=root; pwd=1234;" /> </connectionStrings>

  1. I opened "Package Manager Console" and wrote:

Enable-Migrations -Force

but I got these errors:

Checking if the context targets an existing database...
System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.
   at System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue)
   at System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey)
   at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules)
   at System.Data.Common.DbConnectionStringBuilder.set_ConnectionString(String value)
   at MySql.Data.MySqlClient.MySqlConnectionStringBuilder..ctor(String connStr)
   at MySql.Data.MySqlClient.MySqlConnection.set_ConnectionString(String value)
   at MySql.Data.MySqlClient.MySqlConnection..ctor(String connectionString)
   at MySql.Data.Entity.MySqlConnectionFactory.CreateConnection(String connectionString)
   at System.Data.Entity.Internal.LazyInternalConnection.Initialize()
   at System.Data.Entity.Internal.LazyInternalConnection.get_Connection()
   at System.Data.Entity.Internal.LazyInternalContext.get_Connection()
   at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, DbProviderInfo modelProviderInfo, AppConfig config, DbConnectionInfo connectionInfo)
   at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext)
   at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
   at System.Data.Entity.Migrations.Design.MigrationScaffolder..ctor(DbMigrationsConfiguration migrationsConfiguration)
   at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Run()
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
   at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldInitialCreate(String language, String rootNamespace)
   at System.Data.Entity.Migrations.EnableMigrationsCommand.<>c__DisplayClass2.<.ctor>b__0()
   at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Format of the initialization string does not conform to specification starting at index 0.

Help me solve it, thank you!

Upvotes: 3

Views: 6338

Answers (7)

Eugene Podskal
Eugene Podskal

Reputation: 10401

In our particular case we had DbContext in a separate project.

And despite explicitly setting the project in the Add-Migration command with

Add-Migration -Name Migration1 -Project SeparateDbContextProject 

it still failed with

Format of the initialization string does not conform to specification starting at index 0.

Only when the SeparateDbContextProject has been set as a startup project the migration succeeded.

Upvotes: 1

willthiswork89
willthiswork89

Reputation: 617

Hey so the real fix(not the hack that you are doing here)...

It wont tell you this but the real reason the standard base("{DBConnectionName}") is failing is because of a permissions issue on the folder to access the web.config since the migrations are actually run under a different user.

I had this exact problem so what i did is goto the folder where the web.config is housed, 1) right click and goto properties 2) Goto security 3) Add User, Everyone 4)Tick Full Control 5) Goto Advanced 6) Tick the box that says Replace child object permissions with these 7) hit apply 8) rerun the Add-Migration or Enable-Migration and it will work fine.

Hope this helps someone!

Upvotes: 1

Shankar
Shankar

Reputation: 1

Copy your DAL's ( DataAccessLayer) connectionstring (from config file) to the UI layer's config file. And comment DAL's connectionsstring in the config file.

Upvotes: 0

phanf
phanf

Reputation: 821

This also solve my problem using Code First and MSSQL. When in developer IIS the connection worked without passing it to the base(string nameOrConnectionString) parameter but as soon as I published to IIS the code would get the following error. "Format of the initialization string does not conform to specification starting at index 0". I spent a lot of time looking and most of the other forums state the connection string causes this error which is true, but in my case it was not an error in the syntax of the connection string.

public class EntityContext : DbContext
{

    public static EntityContext EntityStatic()
    {
    var entityCnxStringBuilder = new EntityConnectionStringBuilder("");
    var sqlCnxStringBuilder = new SqlConnectionStringBuilder(entityCnxStringBuilder.ProviderConnectionString);
        sqlCnxStringBuilder.DataSource = "DataSource";
        sqlCnxStringBuilder.UserID = "User";
        sqlCnxStringBuilder.Password = "Password";
        sqlCnxStringBuilder.InitialCatalog = "DatabaseName";
        sqlCnxStringBuilder.ConnectTimeout = 10;
        sqlCnxStringBuilder.Enlist = false;
        sqlCnxStringBuilder.Pooling = false;
        sqlCnxStringBuilder.AsynchronousProcessing = true;
        sqlCnxStringBuilder.TrustServerCertificate = true;
        sqlCnxStringBuilder.Encrypt = true;
        conn = sqlCnxStringBuilder.ConnectionString;
        //For reference
        //string conn = "Data Source=localhost;Initial Catalog=;User ID=root;Password=1234;";
        return new EntityContext(conn);
    }

    public EntityContext(string conn) : base(conn)
    {    

    }
}

To use this code from your controllers

var myEntity = EntityContext.EntityStatic();

Upvotes: 0

Hoan Tran
Hoan Tran

Reputation: 385

Solved

  • I have tried to change base("myDbContext") to base("name=myDbContext"), but it throw the errer: "No connection string named 'myDbContext' could be found in the application config file."

  • I have been searching and decided copying the connectionString to base: base("server=localhost;user id=root;password=1234;persistsecurityinfo=True;database=dbtest") and it worked.

Upvotes: 9

Lulus Young
Lulus Young

Reputation: 43

<connectionStrings>
    <add name="TravelMobileEntities" connectionString="metadata=res://*/ServerDatabaseModel.csdl|res://*/ServerDatabaseModel.ssdl|res://*/ServerDatabaseModel.msl;provider=MySql.Data.MySqlClient;provider connection string=&quot;server=localhost;user id=YS;password=snys19931103;persistsecurityinfo=True;database=travelmobile&quot;" providerName="System.Data.EntityClient"/></connectionStrings>

Hum...I have no idea where actual problem is. In my case, I'm not using "Code First" pattern. But "EF with MySQL". Above is my connection string which works perfectly good, hope this may help you. If you've solved your problem, please let me know where it is.

Upvotes: 0

nvoigt
nvoigt

Reputation: 77285

Data Source=localhost; port=3306; Initial Catalog=dbtest; uid=root; pwd=1234;

This seems to be MS-SQL syntax. I don't know if MySql supports it. Try:

Server=localhost; port=3306; Database=dbtest;uid=root;pwd=1234;

Upvotes: 0

Related Questions