NHibernate的相对路径连接字符串

时间:2012-10-16 23:00:31

标签: c# nhibernate connection-string relative-path

我正在使用以下代码使用NHibernate创建Session Factory。我想用相对路径指定这条路径,这样当我和我的队友合并我们的分支时,我们不必继续修复连接字符串。我怎么能做到这一点?

private static void InitializeSessionFactory(bool deleteSchemaOnClosing = false, bool regenerateSchemaOnOpening = false)
{
_sessionFactory = Fluently.Configure()
    .Database(MsSqlConfiguration.MsSql2008
                  .ConnectionString(
                      @"Data Source=.\SQLEXPRESS;AttachDbFilename=""C:\MyProject\MyProjectCore\Fluent NHibernate\CoreDatabase.mdf"";Integrated Security=True;User Instance=True")
                  .ShowSql()
    )
    .Mappings(m =>
              m.FluentMappings
                  .AddFromAssemblyOf<User>())
    .ExposeConfiguration(cfg => new SchemaExport(cfg)
                                    .Create(deleteSchemaOnClosing,regenerateSchemaOnOpening))
    .BuildSessionFactory();
}

我的app.config文件如下所示:

<?xml version="1.0"?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="CoreDatabase.Properties.Settings.CoreDatabaseConnectionString"
            connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\CoreDatabase.mdf;Integrated Security=True;User Instance=True"
            providerName="System.Data.SqlClient" />
        <add name="Fluent_NHibernate.Properties.Settings.CoreDatabaseConnectionString"
            connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\CoreDatabase.mdf;Integrated Security=True;User Instance=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client"/></startup></configuration>

谢谢!

2 个答案:

答案 0 :(得分:3)

看看SqlConnectionStringBuilder,您可以执行以下操作:

var rawStr = Settings.CoreDatabaseConnectionString.ConnectionString;
// retrieve the original connection string from config file

var conBuilder = new SqlConnectionStringBuilder(rawStr);
conBuilder.AttachDBFilename = Path.GetFullPath(
    Path.Combine(Environment.CurrentDirectory, "CoreDatabase.mdf"));
// if you're doing this in a web environment, swap Environment.CurrentDirectory 
// for HttpRuntime.AppDomainAppPath

_sessionFactory = Fluently.Configure()
    .Database(MsSqlConfiguration.MsSql2008
                  .ConnectionString(conBuilder.ToString())
                  .ShowSql()
    )
// rest of your configuration...

答案 1 :(得分:0)

作为一个例子你可以遵循这样的事情.. 这将是一种将值保存到.Config文件的方法,但只是为了举例说明如何在.Config文件中使用参数。看看这个。

如果你真的需要一个例子

,我还会更容易地回答我的答案
//Add config like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>

  </connectionStrings>
</configuration>


 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(
                                                          "MyConnectionString",
                                                          String.Format("DataSource={0};InitialCatalog={1};IntegratedSecurity={2}",
                                                                         "testing", "testing2", "Testing6")));
            config.Save(ConfigurationSaveMode.Modified, true);
            ConfigurationManager.RefreshSection("connectionStrings");
            MessageBox.Show(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString)

看一看如何阅读Config File以及在链接上试用示例代码并逐步完成代码,这将是一个非常棒的学习经历...... How to read Application Settings from .Config file