简体   繁体   中英

How do I connect to a .sdf local database file in C#

I am using local SQL Server CE database file ( .sdf ) and Entity Framework for my task.

I have created my models and now entity framework should map them to local database.

I have this code in my Main method which inserts some data to database(to check):

var db = new Context()
var blog = new Blog { Name = 'FirstBlog'};
            db.Blogs.Add(blog);
            db.SaveChanges(); 

and this is my connection string:

<connectionStrings>
   <add name="Connection" 
        connectionString="Data source=|DataDirectory|\LocalDB.sdf&quot;" 
        providerName="System.Data.EntityClient" />
</connectionStrings>

when I run this, I get this error:

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

I have tried several connection string but none worked.

How can I fix this?

UPDATE:

As suggested I changed my connection string to be:

<connectionStrings>
   <add name="Connection" 
        connectionString="provider=System.Data.SqlServerCe.4.0;provider connection string=&quot;Data source=|DataDirectory|\LocalDB.sdf&quot;" 
        providerName="System.Data.EntityClient" />
</connectionStrings>

but this gives me the following error:

Some required information is missing from the connection string. The 'metadata' keyword is always required.

First Install this EntityFramework.SqlServerCompact nuget package and then set your connection string to somting like this:

<connectionStrings>
    <add name="connection" connectionString="Data Source=|DataDirectory|\TestDb.sdf"
      providerName="System.Data.SqlServerCe.4.0" />
  </connectionStrings>

**Note:**By default entity framework will create TestDb.sdf if it doesn't exsist in you solutions \\bin\\Debug directory and after deployment it will be in C:\\Users\\YourUserName\\AppData\\Roaming this directory

You are missing Server=(localdb)\\v11.0 in your connection string to indicate that it is a LocalDB connection. In addition to that, you also have &quot in your connection string that should be removed.

Full details as to how your connection string should look like can be found on this MSDN page.

Examples for connections strings can be found here (Scroll down to

我认为这是一个Sql Server Compact文件,因此您的提供程序需要是System.Data.SqlServerCe提供程序之一。

<connectionStrings>
    <add name="MyCS" connectionString="Data Source=|DataDirectory|\Database1.sdf"
      providerName="System.Data.SqlServerCe.4.0" />
  </connectionStrings>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM