-1

我正在为我的应用程序制作一个小型数据库引导实用程序。我需要从我的模型类创建一个数据库,但我希望能够设置数据库文件名和位置。

如果我执行默认 DbContext 实例化 - 它将尝试创建名为 DataAccessModule.DbContext 的 Db,并且数据库文件(mdf 和 ldf)将位于 Program Files\SQL... 文件夹中。我需要使用我的名称(由用户在引导应用程序的 UI 中输入)以及位于用户选择的文件夹中的 mdf 和 ldf 文件创建数据库。

我怎样才能做到这一点?

4

1 回答 1

0

You need to build a connectionstring like this:

SqlConnectionStringBuilder sqlBldr = new SqlConnectionStringBuilder();
sqlBldr.DataSource = "Server name";
sqlBldr.InitialCatalog = "Database name";
sqlBldr.IntegratedSecurity = true; // or use use + password
sqlBldr.MultipleActiveResultSets = true;

EntityConnectionStringBuilder entBldr = new EntityConnectionStringBuilder();
entBldr.ProviderConnectionString = sqlBuilder.ToString();
entBldr.Metadata = "res://*/";
entBldr.Provider = "System.Data.SqlClient";

The EF connection string is entityBuilder.ToString(). You simply has to use it in your DbContextBuilder. Expose the inherited constructor which receives one parameter:

public class MyDbContext
{
    public MyDbContext(strinc connStr)
        : base(connStr)
    {
    }

    // ...
}

Then use it like this:

string connectionString = // ... use your connection string builder for this

using(MyDbContext ctx = new MyDbContext(connectionString))
{
   // ...
}

For choosing file names and location

Note that you can specify the full path to the .mdf file in the AttachDBFilename property of your SqlConnectionStringBuilder property instead of using server + database. See SqlConnectionStringBuilder MSDN docs for more information.

However, you must ensure that, uf the user specifies a folder, she must have read/write access to that folder.

于 2014-06-15T11:05:32.363 回答