Extreme newbie question. I have my database (SQL Server) configured for cascading deletes for my relationships, so if you delete the parent object, all children are also deleted ( ON DELETE CASCADE ). I want this to reflect on my unattended installation of Fluent NHibernate. However, when I try to delete a child, NHibernate instead tries to set the relation key to NULL.
The database is super simple: ( -- for "one", -< for "many")
User ---< UserCode >--- Code >--- CodeGroup
When I delete CodeGroup , it deletes the cascade to Code and UserCode . When I delete the code, it should just cascade to UserCode , but leave the CodeGroup untouched.
My objects (properties removed for clarity):
public class User { public virtual IList<Code> FoundCodes { get; private set; } } public class Code { public virtual IList<User> UsersWithCode { get; private set; } public virtual CodeGroup CodeGroup { get; set; } } public class CodeGroup { public virtual IList<Code> Codes { get; private set; } }
This is what SessionFactory looks like:
var _sessionFactory = Fluently.Configure() .Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2005.ConnectionString(c => c.FromConnectionStringWithKey("db")).ShowSql()) .Cache(csb => csb.UseQueryCache()) .Mappings(m => m.AutoMappings.Add( AutoMap.AssemblyOf<Code>(new AutomappingConfiguration()) .Override<User>(map => map.HasManyToMany(u => u.FoundCodes).Table("UserCode")) .Override<Code>(map => map.HasManyToMany(c => c.UsersWithCode).Inverse().Table("UserCode")) .Conventions.Add(new CustomForeignKeyConvention()))) .BuildSessionFactory())
But when I do this:
using (var tx = _db.BeginTransaction()) { var codeGroup = _db.Load<CodeGroup>(id); _db.Delete(codeGroup); tx.Commit(); }
I get this:
could not delete collection: [MidnightRoseRace.Data.Entities.CodeGroup.Codes
All he needs to do is delete, but instead he tries to set the invalid foreign key to null. What's happening?