views:

96

answers:

1

I am trying a very simple Fluent Nhibernate example: SQL 2005 database with one table, VS2008 console application. The table has one record before the program starts.

I am trying to add one record, then display all records from table. Programs successfully compiles and runs without any exceptions, however no records are displayed. HBM mapping file is not created either. It looks like that the program totally ignores the database (although it connects to it).

Here is my code - I tried to keep it minimal:

Entity:

namespace FluentNhibernationConsole.Entities
{
    public class Sorder
    {
        public virtual int Id { get; private set; }
        public virtual DateTime DateCreated { get; set; }

    }
}

Mapping:

namespace FluentNhibernationConsole.Mappings
{
    class SorderMap : ClassMap<Sorder>
    {
        public SorderMap()
        {
            Id(x => x.Id, "SorderId");
            Map(x => x.DateCreated);
        }
    }
}

Program itself:

namespace FluentNhibernationConsole
{
    class Program
    {
         private static ISessionFactory CreateSessionFactory()
        {
            return Fluently.Configure()
                .Database(MsSqlConfiguration
                    .MsSql2005
                    .ShowSql()
                    .ConnectionString(@"server=.\sqlexpress;database=lsdb;Integrated Security=SSPI;")
                )
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Program>()
                    .ExportTo(@"d:\temp\nh")
                )
                .BuildSessionFactory();
        }

        static void Main(string[] args)
        {
            var sessionFactory = CreateSessionFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    var order1 = new Sorder {DateCreated = DateTime.Now};
                    transaction.Commit();
                }
                using (session.BeginTransaction())
                    foreach (var order in session.CreateCriteria(typeof(Sorder)).List<Sorder>())
                        Console.WriteLine("Order: " + order.DateCreated.ToLongTimeString());
            }
            Console.ReadKey();
        }

    }
}
+1  A: 

As you have already noted, you forgot to Save() your new entity.

using (var transaction = session.BeginTransaction())
{
    var order1 = new Sorder {DateCreated = DateTime.Now};
    session.Save( order1 );
    transaction.Commit();
}

And your ClassMap should be public

public class SorderMap : ClassMap<Sorder>
Lachlan Roche
Oh, thanks, now I see where I've screwed it up. It is all working now :)
Alexey