Why do I get “Database already exists” when I'm using “AttachDbFileName” when I move the solution to another directory?

前端 未结 3 393
被撕碎了的回忆
被撕碎了的回忆 2021-01-24 02:32

I have an application JigSaw that uses a database TopScores.mdf which it is not included in the project. What I want to do is make the application find the database

相关标签:
3条回答
  • 2021-01-24 02:40

    This is happening because you don't leverage the User Instance=true; when you connect to it. You literally told SQL Server to attach the database to the running SQL instance from the directory you first loaded it from.

    Detach the database by hand from the running SQL instance, change your connection string to use User Instance=true;, run it from the Debug folder, and then run it from the Desktop, and you'll see success.

    0 讨论(0)
  • 2021-01-24 02:42

    just rename ur .mdf file ... eg. from MNGMT.mdf to M_1(something you want). change your contact string...hope so it will help u.. in my case it is executing correctly on other pc as well as in my pc.. just copy your .mdf file into you project ..

    string dbPath = Path.GetDirectoryName(Application.ExecutablePath) + "\\M_1.mdf";
    string myServer = Environment.MachineName;
    DataTable servers = SqlDataSourceEnumerator.Instance.GetDataSources();
                for (int i = 0; i < servers.Rows.Count; i++)
                {
                    if (myServer == servers.Rows[i]["ServerName"].ToString()) ///// used to get the servers in the local machine////
                    {
                        if ((servers.Rows[i]["InstanceName"] as string) != null)
                            servername = (servers.Rows[i]["ServerName"] + "\\" + servers.Rows[i]["InstanceName"]);
                        else
                            servername = ""+servers.Rows[i]["ServerName"];
                    }
                }
    connetionString = "Data Source=" + servername + ";AttachDbFilename=" + dbPath + ";Integrated Security=True;Pooling=False;User Instance=True";
    
    0 讨论(0)
  • 2021-01-24 02:44

    change setting in your connection string from "Database=TopScores.mdf" to something different, say: "Database=TopScores_brand_new_connection" do not create/delete/rename files in any file/database server. do it in the connection string only. Do not add dots, extensions etc.

    0 讨论(0)
提交回复
热议问题