Keyword not supported: 'attachdbfilename' - MDF Database File (C#)

痞子三分冷 提交于 2021-01-28 04:41:17

问题


I trying connect to my .MDF file but I am not able to accomplish it. I tried various variations of connection strings but still getting this same error.

This my connection string from app.config

<connectionStrings>
    <add name="DBConnection"
         connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\iseo-db.mdf;Integrated Security=True"
         providerName="System.Data.SqlClient" />
</connectionStrings>

and this is how I call this connection string

private string connection = System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ToString();

SqlCeConnection con = new SqlCeConnection(connection);

When every I try execute I get a exception saying

Keyword not supported: 'attachdbfilename'

I would really appreciate any help on this problem.


回答1:


As far as i know, SQL-Server CE does not use mdf files, rather than sdf files. Futhermore you don't have to use the property AttachDbFilename, then simply use the property Data Source=....

 <add name="DBConnection"
      connectionString="Data Source=|DataDirectory|/iseo-db.sdf;Integrated Security=True"
      providerName="System.Data.SqlServerCe.4.0" />

Some thing like this should do the trick.

EDIT

According to @marc_s, the data provider also has to be changed to: System.Data.SqlServerCe.4.0




回答2:


You should use SqlConnection if you are using LocalDB. LocalDB is not SQL Server compact edition. It is the full SQL Server.

Compact edition is deprecated and you shouldn't use it. Per documentation, you can use LocalDB if you want a "local file" database just like compact edition. But it works with the full SQL Server provider. That is why you are getting this exception.

Your configuration is fine. You just have to change you connection creation code to use SqlConnection instead of SqlCeConnection.

private string connection = System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ToString();

SqlConnection con = new SqlConnection(connection);

I know you have accepted the other answer. I don't care. I just want to warn people against continuing to use SQL Server CE. You will have trouble in the near future.




回答3:


As you are using .mdf file you can't use SqlCeConnection instead you should use SqlConnection to connect to the database. For that, you need to use System.Data and System.Data.SqlClient.

private string connection ="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\iseo-db.mdf;Integrated Security=True" 

SqlConnection con = new SqlConnection(connection);

Make sure that you are not using SqlCe any where in your code.



来源:https://stackoverflow.com/questions/34444170/keyword-not-supported-attachdbfilename-mdf-database-file-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!