Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

c# - EF 5 + SQL Server CE 4: How to specify custom location for database file?

I am developing a client system that needs a small local database. I want to avoid installation of SQL Server Express and have decided to go with SQL Server 4.

I use Entity Framework 5 for data access and have created my custom context. Everything works fine in development where I can use app.config to either set specific file location or dynamic Data Source=|DataDirectory|MyDatabase.sdf.

But on deploy I want the database to be located in the users documents folder:

My DocumentsApplicationNameMyDatabase.sdf

How can I do that?

All I need is actually to be able to set custom connection string in code!

This is what I tried so far:

private MyApplicationDataContext(string connectionString)
    : base(connectionString)
{
}

public static MyApplicationDataContext CreateInstance()
{
    var directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    var path = Path.Combine(directory, @"ApplicationNameMyDatabase.sdf");

    //var connectionString = string.Format("provider=System.Data.SqlServerCe.4.0;provider connection string="Data Source={0}"", path);
    var connectionString = string.Format("Data Source={0}", path);

    return new MyApplicationDataContext(connectionString);
}

As you can see I tried two kinds of connection strings but both caused exceptions.

Keyword not supported: 'provider'.

and

The provider did not return a ProviderManifestToken string.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Ah, I finally got it right!

I include the adjusted code if someone else has the same problem. The trick was to set the connection string on the Database.DefaultConnectionFactory

    private MyApplicationDataContext()
    { }

    public static MyApplicationDataContext CreateInstance()
    {
        var directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        var path = Path.Combine(directory, @"ApplicationNameMyDatabase.sdf");

        // Set connection string
        var connectionString = string.Format("Data Source={0}", path);
        Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0", "", connectionString);

        return new MyApplicationDataContext();
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...