EF 5 + SQL Server CE 4:如何为数据库文件指定自定义位置? [英] EF 5 + SQL Server CE 4: How to specify custom location for database file?

查看:86
本文介绍了EF 5 + SQL Server CE 4:如何为数据库文件指定自定义位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个需要小型本地数据库的客户端系统。
我想避免安装SQL Server Express,并决定使用SQL Server 4。

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.

我使用Entity Framework 5进行数据访问,并创建了自定义上下文。
开发过程中一切正常,我可以使用app.config设置特定文件位置或动态 Data Source = | DataDirectory | \MyDatabase.sdf

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 Documents\ApplicationName\MyDatabase.sdf

我该怎么做?

我真正需要的只是能够在代码中设置自定义连接字符串!

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, @"ApplicationName\MyDatabase.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.


不支持关键字: provider。

Keyword not supported: 'provider'.


提供程序未返回ProviderManifestToken字符串。

The provider did not return a ProviderManifestToken string.


推荐答案

啊,我终于明白了!

如果其他人有,我会提供调整后的代码同样的问题。
诀窍是在Database.DefaultConnectionFactory

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, @"ApplicationName\MyDatabase.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();
    }

这篇关于EF 5 + SQL Server CE 4:如何为数据库文件指定自定义位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆