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);