如何使用流畅的 nhibernate (schemaexport) 测试生成表?在 ASP.NET 上下文中

发布于 2024-10-03 10:28:45 字数 3117 浏览 6 评论 0原文

嗯,这是我第一个使用流畅的 hibernate 的项目。我在 hibernate 和 nhibernate 方面有一些经验。

这个上下文对我来说是全新的,因为这是一个网络应用程序项目。 所以我有我的 webapp 项目,其中包含在网上找到的大多数流畅的 nhibernate。 所以我有这个实体:

namespace myproject.model
{
  public class Request
  {
    public virtual string Id { get; private set; }
    public virtual Route route { get; set; }
    public virtual int code { get; set; }

  }
}

namespace myproject.model
{
  public class Route
  {
    public virtual string Id { get; private set; }
    public virtual string client_id { get; set; }
    public virtual IList<Request> requests { get; set; }

    public Route()
    {
        requests = new List<Request>();
    }

  }

}

//Mapping are like this.will only post one
namespace myproject.mappings
{
 public class RequestMap : ClassMap<Request>
 {
    public RequestMap()
    {
        Id(x => x.Id);
        Map(x => x.short_code);
        References(x => x.route);
    }
  }
}

//NhibernateSessionPerRequest
namespace myproject.Boostrap
{
  public class NhibernateSessionPerRequest : IHttpModule
  {
    private static readonly ISessionFactory _sessionFactory;

    static NhibernateSessionPerRequest()
    {
        _sessionFactory = CreateSessionFactory();
    }

    //all others IHttpModule event and methods are here
    private static ISessionFactory CreateSessionFactory()
    {

        FluentConfiguration configuration = Fluently.Configure().Database(MsSqlConfiguration.MsSql2005.
                                                                              ConnectionString(x => x.FromConnectionStringWithKey("localdb")))
            .Mappings(m => {
                            m.FluentMappings.AddFromAssemblyOf<myproject.model.Request>();
                            m.FluentMappings.AddFromAssemblyOf<myproject.model.Route>();
                           }
                     ).ExposeConfiguration((c)=> savedConfig = c);;

        return configuration.BuildSessionFactory();
    }

  }

   private static Configuration savedConfig;

    public static void BuildSchema(NHibernate.Cfg.Configuration config)
    {
        new SchemaExport(config).Create(false, true);
    }

    public static void BuildSchema(ISession session)
    {
        var export = new SchemaExport(savedConfig);
        export.Execute(false,true,false,session.Connection,null);
    }


}

我在 webconfig 中添加了模块,

  <add name="NhibernateSessionPerRequest" type="myproject.Boostrap.NhibernateSessionPerRequest"/>

以便测试表的生成,我添加了一个测试项目(类库),添加了对 nunit.framework 2.8.5 和 myproject 的引用。

namespace myproject.Tests
{
  [TestFixture]
  public class CanGenerateSchemaTestSuite
  {
    [Test]
    public void CanGenarateSchema()
    {
       NhibernateSessionPerRequest.BuildSchema(NhibernateSessionPerRequest.GetCurrentSession());

     }
  }
}

测试方法总是失败,我遇到了这个异常:

CanGenerateSchemaTestSuite(1 个测试),1 个测试失败:子测试失败 CanGenerateSchema,失败:System.TypeInitializationException

那么如何在 asp.net 上下文中进行测试? 感谢您阅读本文。谢谢

well this is my very very first project with fluent hibernate.i've had small experience in hibernate and nhibernate.

This context is completely new to me since this is a web app project.
So i have my webapp project with most of the fluent nhibernate found on the net.
so i have This entities:

namespace myproject.model
{
  public class Request
  {
    public virtual string Id { get; private set; }
    public virtual Route route { get; set; }
    public virtual int code { get; set; }

  }
}

namespace myproject.model
{
  public class Route
  {
    public virtual string Id { get; private set; }
    public virtual string client_id { get; set; }
    public virtual IList<Request> requests { get; set; }

    public Route()
    {
        requests = new List<Request>();
    }

  }

}

//Mapping are like this.will only post one
namespace myproject.mappings
{
 public class RequestMap : ClassMap<Request>
 {
    public RequestMap()
    {
        Id(x => x.Id);
        Map(x => x.short_code);
        References(x => x.route);
    }
  }
}

//NhibernateSessionPerRequest
namespace myproject.Boostrap
{
  public class NhibernateSessionPerRequest : IHttpModule
  {
    private static readonly ISessionFactory _sessionFactory;

    static NhibernateSessionPerRequest()
    {
        _sessionFactory = CreateSessionFactory();
    }

    //all others IHttpModule event and methods are here
    private static ISessionFactory CreateSessionFactory()
    {

        FluentConfiguration configuration = Fluently.Configure().Database(MsSqlConfiguration.MsSql2005.
                                                                              ConnectionString(x => x.FromConnectionStringWithKey("localdb")))
            .Mappings(m => {
                            m.FluentMappings.AddFromAssemblyOf<myproject.model.Request>();
                            m.FluentMappings.AddFromAssemblyOf<myproject.model.Route>();
                           }
                     ).ExposeConfiguration((c)=> savedConfig = c);;

        return configuration.BuildSessionFactory();
    }

  }

   private static Configuration savedConfig;

    public static void BuildSchema(NHibernate.Cfg.Configuration config)
    {
        new SchemaExport(config).Create(false, true);
    }

    public static void BuildSchema(ISession session)
    {
        var export = new SchemaExport(savedConfig);
        export.Execute(false,true,false,session.Connection,null);
    }


}

I've added the module in webconfig

  <add name="NhibernateSessionPerRequest" type="myproject.Boostrap.NhibernateSessionPerRequest"/>

in order to test the generation of the tables i've added a test project (class library) added ref to nunit.framework 2.8.5 and myproject.

namespace myproject.Tests
{
  [TestFixture]
  public class CanGenerateSchemaTestSuite
  {
    [Test]
    public void CanGenarateSchema()
    {
       NhibernateSessionPerRequest.BuildSchema(NhibernateSessionPerRequest.GetCurrentSession());

     }
  }
}

the test method always fails, and i'm having this exception:

CanGenerateSchemaTestSuite (1 test), 1 test failed: Child test failed
CanGenarateSchema, Failed: System.TypeInitializationException

so how testing is being done in an asp.net context??
thanks for reading this.thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

┈┾☆殇 2024-10-10 10:28:45

只是对其他解决方案的模糊评论;您不需要为此完全删除数据库文件;只需删除表:

.ExposeConfiguration(SetupTestDatabase)

...

private static void SetupTestDatabase(NHibernate.Cfg.Configuration config)
{
    var schema = new SchemaExport(config);
    schema.Drop(true, true);
    schema.Create(true, true);
}

这仅意味着您可以在不同的数据库上运行测试,而无需更改任何其他内容。

编辑;哎呀;认为这是一个可以接受的解决方案。如果您在测试中这样做,只需这样做:

   [Test]
    public void Test_can_store_and_get_objects()
    {
        var factory = CreateSessionFactory();
        using (var s = factory.OpenSession())
        { 
             ...
        }
    }

    private static ISessionFactory CreateSessionFactory()
    {
        return Fluently.Configure().Database(SQLiteConfiguration.Standard.UsingFile("firstProject.db"))
        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Address>()) // <-- Refer to parent project
        .ExposeConfiguration(SetupTestDatabase)
        .BuildSessionFactory();
    }

Just a vague comment on the other solution; you don't need to delete database files completely for this; just drop the tables:

.ExposeConfiguration(SetupTestDatabase)

...

private static void SetupTestDatabase(NHibernate.Cfg.Configuration config)
{
    var schema = new SchemaExport(config);
    schema.Drop(true, true);
    schema.Create(true, true);
}

It just means you can run your tests on a different database without changing anything else.

Edit; woops; thought that was an accepted solution. If you're doing it in a test, just do it like this:

   [Test]
    public void Test_can_store_and_get_objects()
    {
        var factory = CreateSessionFactory();
        using (var s = factory.OpenSession())
        { 
             ...
        }
    }

    private static ISessionFactory CreateSessionFactory()
    {
        return Fluently.Configure().Database(SQLiteConfiguration.Standard.UsingFile("firstProject.db"))
        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Address>()) // <-- Refer to parent project
        .ExposeConfiguration(SetupTestDatabase)
        .BuildSessionFactory();
    }
溇涏 2024-10-10 10:28:45

这是我的一个例子。您需要使用 ExposeConfiguration 并传递一个接受配置的方法,然后您只需在那里构建数据库,然后使用 SchemaExport

class SqliteRefSessionFactoryProvider : ISessionFactoryProvider
{

    public const string SqliteRefFileName = "ref.db";

    public ISessionFactory GetSessionFactory()
    {
        return Fluently.Configure().Database(
            SQLiteConfiguration.Standard.UsingFile(SqliteRefFileName).ShowSql())
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<SsoToken>())
            .ExposeConfiguration(BuildSchema)
            .BuildSessionFactory();
    }

    private static void BuildSchema(NHibernate.Cfg.Configuration configuration) 
    {
        if (File.Exists(SqliteRefFileName))
            File.Delete(SqliteRefFileName);

        new SchemaExport(configuration)
          .Create(false, true);
    }
}

Here is an example of mine. You need to use ExposeConfiguration and pass a method which accepts a configuration and you just build the database there and then using SchemaExport:

class SqliteRefSessionFactoryProvider : ISessionFactoryProvider
{

    public const string SqliteRefFileName = "ref.db";

    public ISessionFactory GetSessionFactory()
    {
        return Fluently.Configure().Database(
            SQLiteConfiguration.Standard.UsingFile(SqliteRefFileName).ShowSql())
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<SsoToken>())
            .ExposeConfiguration(BuildSchema)
            .BuildSessionFactory();
    }

    private static void BuildSchema(NHibernate.Cfg.Configuration configuration) 
    {
        if (File.Exists(SqliteRefFileName))
            File.Delete(SqliteRefFileName);

        new SchemaExport(configuration)
          .Create(false, true);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文