0

I have a proglem with nhibernate fluent with C# + MVC. It doesn't make id unique.

I run my application. Add post. Its id is 1.

I stopped my app. Then I run it again and if i create new record it is generated id 1 for another post and write it over previous.

public class Post
{
    public virtual int Id { get; set; }
    public virtual string Title { get; set; }
    public virtual string ShortDescription { get; set; }
    ...     
}

Mapping

public class PostMap : ClassMap<Post>
{
    public PostMap()
    {
        Id(x => x.Id);            

        Map(x => x.Title)
            .Length(500);
        ...   

Helper

public class NHibernateHelper
{
    private static ISessionFactory _sessionFactory;

    private static ISessionFactory SessionFactory
    {
        get
        {
            if (_sessionFactory == null)

                InitializeSessionFactory();
            return _sessionFactory;
        }
    }


    private static void InitializeSessionFactory()
    {
        _sessionFactory = Fluently.Configure()
                    .Database(MsSqlConfiguration.MsSql2012
                    .ConnectionString(c => c.FromConnectionStringWithKey("DefaultConnection")))                
                    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Post>())
                    .ExposeConfiguration(cfg => new SchemaExport(cfg)
                                            .Create(true, true))
            .BuildSessionFactory();            
    }


    public static ISession OpenSession()
    {
        return SessionFactory.OpenSession();
    }
}    

Blog repository

public class  BlogRepository 
{ 
   public int AddPost(Post post)
    {
        using (var session = NHibernateHelper.OpenSession())
        {
            using (var tran = session.BeginTransaction())
            {
                session.Save(post);
                tran.Commit();
                return post.Id;
            }
        }
    }

code snippet:

var _blogRepository = new BlogRepository(); 
var post = new Post(); 
post.Title = "Form den3"; 
post.PostedOn = DateTime.Now; 
post.Modified = DateTime.Now; 
var postID = _blogRepository.AddPost(post);
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
Smart Why
  • 1
  • 1

1 Answers1

1

Mapping as is, should be ok and should use Identity (the default). And this line:

Id(x => x.Id).GeneratedBy.Identity()

should assure, that the identity is used. But as said in comments, it is not working either.

The most suspected to me is this piece of code:

new SchemaExport(cfg).Create(true, true))

This in fact DROPS the tables and recreate them. Which could end up in "regenerated" id == 1.

So, try to not use that, if really needed use just .Update()

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335