I'm still struggeling with this issue. It seems such a basic thing to
me.. Maybe it will help if i post all the code.
Entities:
using System;
namespace Blog.Logic
{
public class Comment
{
public Comment() { }
public virtual Int32 Id { get; private set; }
public virtual String Text { get; set; }
public virtual Post Post { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Blog.Logic
{
public class Post
{
public Post()
{
Comments = new Collection<Comment>();
}
public virtual void AddComment(Comment c)
{
c.Post = this;
Comments.Add(c);
}
public virtual Int32 Id { get; private set; }
public virtual String Title { get; set; }
public virtual String Content { get; set; }
public virtual DateTime PostDate { get; set; }
public virtual ICollection<Comment> Comments { get; private
set; }
}
}
Mapping files:
using FluentNHibernate.Mapping;
namespace Blog.Logic
{
public class CommentMap : ClassMap<Comment>
{
public CommentMap()
{
Id(x => x.Id);
Map(x => x.Text);
References(x => x.Post);
}
}
}
using FluentNHibernate.Mapping;
namespace Blog.Logic
{
public class PostMap : ClassMap<Post>
{
public PostMap()
{
Id(x => x.Id);
Map(x => x.Title);
Map(x => x.Content);
Map(x => x.PostDate);
HasMany(x => x.Comments).Cascade.AllDeleteOrphan();
}
}
}
How i build the session factory and created the database (i comment
the database part after i generated it):
Configuration cfg = new Configuration();
cfg.SetProperty(NHibernate.Cfg.Environment.Dialect,
"NHibernate.Dialect.MsSql2005Dialect");
cfg.SetProperty(NHibernate.Cfg.Environment.ConnectionProvider,
"NHibernate.Connection.DriverConnectionProvider");
cfg.SetProperty(NHibernate.Cfg.Environment.ConnectionDriver,
"NHibernate.Driver.SqlClientDriver");
cfg.SetProperty(NHibernate.Cfg.Environment.ConnectionString, "Server=.\
\SQLEXPRESS; Database=Blog;Integrated Security=SSPI;");
cfg.SetProperty(NHibernate.Cfg.Environment.Isolation,
"ReadCommitted");
cfg.SetProperty(NHibernate.Cfg.Environment.CurrentSessionContextClass,
"managed_web");
cfg.SetProperty(NHibernate.Cfg.Environment.DefaultSchema,
"Blog.dbo");
cfg.SetProperty(NHibernate.Cfg.Environment.ShowSql,
"true");
cfg.SetProperty(NHibernate.Cfg.Environment.ProxyFactoryFactoryClass,
"NHibernate.ByteCode.Castle.ProxyFactoryFactory,
NHibernate.ByteCode.Castle");
cfg.AddAssembly("Blog.Logic");
sessionFactory = Fluently
.Configure(cfg)
.Mappings(
m => m.FluentMappings.AddFromAssemblyOf<SessionManager>()
).BuildSessionFactory();
// Create Database
SchemaExport schema = new SchemaExport(cfg);
schema.Drop(false, true);
schema.Create(false, true);
How i delete the Comment:
sessionManager.sessionFactory.GetCurrentSession().Delete(entity);