Search code examples
c#-4.0nhibernatedatasetnhibernate-mappingfluent-nhibernate-mapping

Is it possible to use NHibernate with just Dataset in c#


Sorry, if this is silly question. Is it possible to use NHibernate with just Dataset in c#? I mean I don't intend to have any database but will update my other application upon events triggered over datatables or datarows. I want to have hibernate mappings to these dataset tables and want to use static implementation for event handlers. So all the changes to the dataset can be tracked in single static class which has multiple event handlers. So that except for my updates to other application, I want to use NHibernate.


Solution

  • I think that your question may need some more clarification to add more details, but I will just give my thoughts to it.

    Basics

    Basically NHibernate is an Object-Relational Mapper, that is, it maps your persistence models to (whatever is your choice database) tables and it fields and vice versa.

    What you are really about is to not have a database backed by NHibernate, and rather change this behaviour to work with DataTables/DataRows. This can be done via enormous hacking and plumbing, but if I would be you, I would just try to save myself from that.

    A way to do it

    The easiest way I would do this by using a file-based or in-memory persistence represantation, these could be for instance SQLite or SQL Server Express. I use the in-memory SQLite for NHibernate persistence unit tests.

    You may need to configure NHibernate (using FluentNHibernate) to use SQLite database as:

    ISessionFactory _sessionFactory = Fluently.Configure()
            .Database(SQLiteConfiguration.Standard.InMemory().ShowSql())
            .Mappings(m => m.FluentMappings.AddFromAssembly(assemblyContainingMappedType))
            //.Mappings(m => m.AutoMappings.Add(AutoMap.Assembly(assemblyContainingMappedType)))
            .ExposeConfiguration(cfg => _configuration = cfg)
    #if DEBUG 
            .Diagnostics(d => d.Enable())
            .Diagnostics(d => d.OutputToConsole())
    #endif
            .BuildSessionFactory();
    

    This way you have an ISessionFactory instance. Now by using your Fluent mapping just execute:

    ISession _session = _sessionFactory.OpenSession();
    new SchemaExport(_configuration).Execute(true, true, false, _session.Connection, Console.Out);
    

    Now you have the in-memory SQLite up and running. The only thing you need to implement is to work with NHibernate's ISession (eg.: _session.Save()) to work with the database and have your repositories or queries return DataSet or DataTable.