Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3946388
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T01:07:39+00:00 2026-05-20T01:07:39+00:00

Why is the parent (Store) deleted when I delete a child (Employee) ? I

  • 0

Why is the parent (Store) deleted when I delete a child (Employee)?

I configure with convention Cascade.All.

The user input sequence is quite simple:

  • Start with empty database
  • Add a parent
  • Save, Load (Load = reload full object graph)
  • Add a child
  • Save, Load
  • Delete Child
  • Result: Empty database. (Parent deleted)

It could be a basic mapping mistake, as it’s my first take on NHibernate. I want Store to be the aggregate root, and thought that by not setting Inverse on the Store.Staff property, then Store table would be responsible for saving, and hence the aggregate root. Is that a misconception? Actually if I use Inverse or not I still get the same result. So maybe
that’s not the problem, but I would like to understand that too.

And it’s deliberate not to use a wider session scope, as I want to learn how to work with detached and transient entities.

Employee Delete Method:

class EmployeeRepository
        public static void Delete(Employee employee)
        {
            using (ISession session = FNH_Manager.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    if (employee.Id != 0)
                    {
                      var emp =  session.Get(typeof(Employee), employee.Id);

                      if (emp != null)
                      {
                        session.Delete(emp);
                        transaction.Commit();
                      }
                    }
                }
            }
        } 

Mappings

public class StoreMap : ClassMap<Store>
{
    public StoreMap()
    {
        Id(x => x.Id);
        Map(x =>  x.Name);
        HasMany(x => x.Staff)    // 1:m
            .Inverse()    // tried both with and without, what is correct?
            .Cascade.All();       
        HasManyToMany(x => x.Products)  // m:m
            .Cascade.All()
            .Table("StoreProduct");    
    }
}

public class EmployeeMap : ClassMap<Employee> 
{

    public EmployeeMap()
    {
        Id(x => x.Id);                // By default an int Id is generated as identity
        Map(x => x.FirstName);
        Map(x => x.LastName);
        References(x => x.Store);    // m:1
    }
}

public class ProductMap : ClassMap<Product>
{
    public ProductMap() 
    {
        Id(x => x.Id).GeneratedBy.Identity();
        Map(x => x.Name).Length(20);
        Map(x => x.Price).CustomSqlType("decimal").Precision(9).Scale(2);
        HasManyToMany(x => x.StoresStockedIn)
        .Cascade.All()
        .Inverse()
        .Table("StoreProduct");
     }

}

Entities:

   public class Store
    {
        public int Id { get; private set; }
        public string Name { get; set; }
        public IList<Product> Products { get; set; }
        public IList<Employee> Staff { get; set; }

        public Store()
        {
            Products = new List<Product>();
            Staff = new List<Employee>();
        }


        // AddProduct & AddEmployee is required. "NH needs you to set both sides before
        // it will save correctly" ??

        public void AddProduct(Product product)
        {
            product.StoresStockedIn.Add(this);
            Products.Add(product);
        }

        public void AddEmployee(Employee employee)
        {
            employee.Store = this;
            Staff.Add(employee);
        }
    }

   public class Employee
    {
        public int Id { get;  private set; }
        public string FirstName { get;  set; }
        public string LastName { get;  set; }
        public Store Store { get; set; }
    }

Program pseudo-code and resulting “SQL”:

Program startup

Load: Stores stores = StoreRepository.GetAll()

NHibernate: SELECT this_.Id as Id3_0_, this_.Name as Name3_0_ FROM [Store] this_

Add parent: Add store to empty collection stores

Save: StoreRepository.SaveOrUpdate(stores)

NHibernate: SELECT store0_.Id as Id3_0_, store0_.Name as Name3_0_ FROM [Store] store0_ WHERE store0_.Id=@p0;@p0 = 0 [Type: Int32 (0)]
NHibernate: INSERT INTO [Store] (Name) VALUES (@p0); select SCOPE_IDENTITY();@p0 = NULL [Type: String (4000)]

Load: stores = StoreRepository.GetAll()

NHibernate: SELECT this_.Id as Id3_0_, this_.Name as Name3_0_ FROM [Store] this_
NHibernate: SELECT products0_.Store_id as Store2_1_, products0_.Product_id as Product1_1_, product1_.Id as Id1_0_, product1_.Name as Name1_0_, product1_.Price as Price1_0_ FROM StoreProduct products0_ left outer join [Product] product1_ on products0_.Product_id=product1_.Id WHERE products0_.Store_id=@p0;@p0 = 16 [Type: Int32 (0)]
NHibernate: SELECT staff0_.Store_id as Store4_1_, staff0_.Id as Id1_, staff0_.Id as Id0_0_, staff0_.FirstName as FirstName0_0_, staff0_.LastName as LastName0_0_, staff0_.Store_id as Store4_0_0_ FROM [Employee] staff0_ WHERE staff0_.Store_id=@p0;@p0 = 16 [Type: Int32 (0)]

Add child: to empty child collection, for selected store

Save: StoreRepository.SaveOrUpdate(stores)

NHibernate: SELECT store0_.Id as Id3_0_, store0_.Name as Name3_0_ FROM [Store] store0_ WHERE store0_.Id=@p0;@p0 = 16 [Type: Int32 (0)]
NHibernate: SELECT products0_.Store_id as Store2_1_, products0_.Product_id as Product1_1_, product1_.Id as Id1_0_, product1_.Name as Name1_0_, product1_.Price as Price1_0_ FROM StoreProduct products0_ left outer join [Product] product1_ on products0_.Product_id=product1_.Id WHERE products0_.Store_id=@p0;@p0 = 16 [Type: Int32 (0)]
NHibernate: SELECT staff0_.Store_id as Store4_1_, staff0_.Id as Id1_, staff0_.Id as Id0_0_, staff0_.FirstName as FirstName0_0_, staff0_.LastName as LastName0_0_, staff0_.Store_id as Store4_0_0_ FROM [Employee] staff0_ WHERE staff0_.Store_id=@p0;@p0 = 16 [Type: Int32 (0)]
NHibernate: INSERT INTO [Employee] (FirstName, LastName, Store_id) VALUES (@p0, @p1, @p2); select SCOPE_IDENTITY();@p0 = NULL [Type: String (4000)], @p1 = NULL [Type: String (4000)], @p2 = 16 [Type: Int32 (0)]

Load: stores = StoreRepository.GetAll()

NHibernate: SELECT this_.Id as Id3_0_, this_.Name as Name3_0_ FROM [Store] this_
NHibernate: SELECT products0_.Store_id as Store2_1_, products0_.Product_id as Product1_1_, product1_.Id as Id1_0_, product1_.Name as Name1_0_, product1_.Price as Price1_0_ FROM StoreProduct products0_ left outer join [Product] product1_ on products0_.Product_id=product1_.Id WHERE products0_.Store_id=@p0;@p0 = 16 [Type: Int32 (0)]
NHibernate: SELECT staff0_.Store_id as Store4_1_, staff0_.Id as Id1_, staff0_.Id as Id0_0_, staff0_.FirstName as FirstName0_0_, staff0_.LastName as LastName0_0_, staff0_.Store_id as Store4_0_0_ FROM [Employee] staff0_ WHERE staff0_.Store_id=@p0;@p0 = 16 [Type: Int32 (0)]

Delete child: (Delete Employee for selected store) EmployeeRepository.Delete(employee)

NHibernate: SELECT employee0_.Id as Id0_1_, employee0_.FirstName as FirstName0_1_, employee0_.LastName as LastName0_1_, employee0_.Store_id as Store4_0_1_, store1_.Id as Id3_0_, store1_.Name as Name3_0_ FROM [Employee] employee0_ left outer join [Store] store1_ on employee0_.Store_id=store1_.Id WHERE employee0_.Id=@p0;@p0 = 35 [Type: Int32 (0)]
NHibernate: SELECT products0_.Store_id as Store2_1_, products0_.Product_id as Product1_1_, product1_.Id as Id1_0_, product1_.Name as Name1_0_, product1_.Price as Price1_0_ FROM StoreProduct products0_ left outer join [Product] product1_ on products0_.Product_id=product1_.Id WHERE products0_.Store_id=@p0;@p0 = 16 [Type: Int32 (0)]
NHibernate: SELECT staff0_.Store_id as Store4_1_, staff0_.Id as Id1_, staff0_.Id as Id0_0_, staff0_.FirstName as FirstName0_0_, staff0_.LastName as LastName0_0_, staff0_.Store_id as Store4_0_0_ FROM [Employee] staff0_ WHERE staff0_.Store_id=@p0;@p0 = 16 [Type: Int32 (0)]
NHibernate: DELETE FROM [Employee] WHERE Id = @p0;@p0 = 35 [Type: Int32 (0)]
NHibernate: DELETE FROM [Store] WHERE Id = @p0;@p0 = 16 [Type: Int32 (0)]

Load: stores = StoreRepository.GetAll()

NHibernate: SELECT this_.Id as Id3_0_, this_.Name as Name3_0_ FROM [Store] this_

(no result, database is empty)


EDIT1:

SQL WITHOUT Inverse

Program startup

Load: Stores stores = StoreRepository.GetAll()

NHibernate: SELECT this_.Id as Id3_0_, this_.Name as Name3_0_ FROM [Store] this_

Add parent: Add store to empty collection stores

Save: StoreRepository.SaveOrUpdate(stores)

NHibernate: SELECT store0_.Id as Id3_0_, store0_.Name as Name3_0_ FROM [Store] store0_ WHERE store0_.Id=@p0;@p0 = 0 [Type: Int32 (0)]
NHibernate: INSERT INTO [Store] (Name) VALUES (@p0); select SCOPE_IDENTITY();@p0 = NULL [Type: String (4000)]

Load: stores = StoreRepository.GetAll()

NHibernate: SELECT this_.Id as Id3_0_, this_.Name as Name3_0_ FROM [Store] this_
NHibernate: SELECT products0_.Store_id as Store2_1_, products0_.Product_id as Product1_1_, product1_.Id as Id1_0_, product1_.Name as Name1_0_, product1_.Price as Price1_0_ FROM StoreProduct products0_ left outer join [Product] product1_ on products0_.Product_id=product1_.Id WHERE products0_.Store_id=@p0;@p0 = 1 [Type: Int32 (0)]
NHibernate: SELECT staff0_.Store_id as Store4_1_, staff0_.Id as Id1_, staff0_.Id as Id0_0_, staff0_.FirstName as FirstName0_0_, staff0_.LastName as LastName0_0_, staff0_.Store_id as Store4_0_0_ FROM [Employee] staff0_ WHERE staff0_.Store_id=@p0;@p0 = 1 [Type: Int32 (0)]

Add child: to empty child collection, for selected store

Save: StoreRepository.SaveOrUpdate(stores)

NHibernate: SELECT store0_.Id as Id3_0_, store0_.Name as Name3_0_ FROM [Store] store0_ WHERE store0_.Id=@p0;@p0 = 1 [Type: Int32 (0)]
NHibernate: SELECT products0_.Store_id as Store2_1_, products0_.Product_id as Product1_1_, product1_.Id as Id1_0_, product1_.Name as Name1_0_, product1_.Price as Price1_0_ FROM StoreProduct products0_ left outer join [Product] product1_ on products0_.Product_id=product1_.Id WHERE products0_.Store_id=@p0;@p0 = 1 [Type: Int32 (0)]
NHibernate: SELECT staff0_.Store_id as Store4_1_, staff0_.Id as Id1_, staff0_.Id as Id0_0_, staff0_.FirstName as FirstName0_0_, staff0_.LastName as LastName0_0_, staff0_.Store_id as Store4_0_0_ FROM [Employee] staff0_ WHERE staff0_.Store_id=@p0;@p0 = 1 [Type: Int32 (0)]
NHibernate: INSERT INTO [Employee] (FirstName, LastName, Store_id) VALUES (@p0, @p1, @p2); select SCOPE_IDENTITY();@p0 = NULL [Type: String (4000)], @p1 = NULL [Type: String (4000)], @p2 = 1 [Type: Int32 (0)]
NHibernate: UPDATE [Employee] SET Store_id = @p0 WHERE Id = @p1;@p0 = 1 [Type: Int32 (0)], @p1 = 1 [Type: Int32 (0)]

Load: stores = StoreRepository.GetAll()

NHibernate: SELECT this_.Id as Id3_0_, this_.Name as Name3_0_ FROM [Store] this_
NHibernate: SELECT products0_.Store_id as Store2_1_, products0_.Product_id as Product1_1_, product1_.Id as Id1_0_, product1_.Name as Name1_0_, product1_.Price as Price1_0_ FROM StoreProduct products0_ left outer join [Product] product1_ on products0_.Product_id=product1_.Id WHERE products0_.Store_id=@p0;@p0 = 1 [Type: Int32 (0)]
NHibernate: SELECT staff0_.Store_id as Store4_1_, staff0_.Id as Id1_, staff0_.Id as Id0_0_, staff0_.FirstName as FirstName0_0_, staff0_.LastName as LastName0_0_, staff0_.Store_id as Store4_0_0_ FROM [Employee] staff0_ WHERE staff0_.Store_id=@p0;@p0 = 1 [Type: Int32 (0)]

Delete child: (Delete Employee for selected store) EmployeeRepository.Delete(employee)

NHibernate: SELECT employee0_.Id as Id0_1_, employee0_.FirstName as FirstName0_1_, employee0_.LastName as LastName0_1_, employee0_.Store_id as Store4_0_1_, store1_.Id as Id3_0_, store1_.Name as Name3_0_ FROM [Employee] employee0_ left outer join [Store] store1_ on employee0_.Store_id=store1_.Id WHERE employee0_.Id=@p0;@p0 = 1 [Type: Int32 (0)]
NHibernate: SELECT products0_.Store_id as Store2_1_, products0_.Product_id as Product1_1_, product1_.Id as Id1_0_, product1_.Name as Name1_0_, product1_.Price as Price1_0_ FROM StoreProduct products0_ left outer join [Product] product1_ on products0_.Product_id=product1_.Id WHERE products0_.Store_id=@p0;@p0 = 1 [Type: Int32 (0)]
NHibernate: SELECT staff0_.Store_id as Store4_1_, staff0_.Id as Id1_, staff0_.Id as Id0_0_, staff0_.FirstName as FirstName0_0_, staff0_.LastName as LastName0_0_, staff0_.Store_id as Store4_0_0_ FROM [Employee] staff0_ WHERE staff0_.Store_id=@p0;@p0 = 1 [Type: Int32 (0)]
NHibernate: UPDATE [Employee] SET Store_id = null WHERE Store_id = @p0;@p0 = 1 [Type: Int32 (0)]
NHibernate: DELETE FROM [Employee] WHERE Id = @p0;@p0 = 1 [Type: Int32 (0)]
NHibernate: DELETE FROM [Store] WHERE Id = @p0;@p0 = 1 [Type: Int32 (0)]

Load: stores = StoreRepository.GetAll()

NHibernate: SELECT this_.Id as Id3_0_, this_.Name as Name3_0_ FROM [Store] this_

(Still; no result, database is empty)

Program window

Store collection and child collection of selected store is bound to BindingSource/DataGridView/BindingNavigator like this:

enter image description here


EDIT2

    private static ISessionFactory CreateSessionFactory()
    {
        if (sessionFactory == null)
        {                              
            return Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008
                .ConnectionString(Properties.Settings.Default.FnhDbString)
                .Cache(c => c
                    .UseQueryCache()).ShowSql())
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<EmployeeMap>()  
                .Conventions.Add(FluentNHibernate.Conventions.Helpers.DefaultLazy.Never())
                .Conventions.Add(FluentNHibernate.Conventions.Helpers.DefaultCascade.All())
                .ExportTo("D:/VB/"))              
                .ExposeConfiguration(c => cfg = c)
                .BuildSessionFactory();
        }
        return sessionFactory; 
    }

EDIT3

I have now tried all different mappings below (1-6). Without cascade-convention, I get exception on all alternatives. Am I forced to delete references manually? I thought it should not be required.

// For all alternatives, configuration does not specify cascade-convention.

//  HasMany(x => x.Staff);   // 1. add store, save, load, add employee, 
                             // save: TransientObjectException; Employee
    HasMany(x => x.Staff).Inverse();       // 2. As 1
//  HasMany(x => x.Staff).Cascade.All();   // 3. Add store, Save, Load, Add Employee, Save, Load, 
                                           // Delete Employee: ObjectDeletedException
//  HasMany(x => x.Staff).Inverse().Cascade.All();              // 4. As 3
//  HasMany(x => x.Staff).Inverse().Cascade.AllDeleteOrphan();  // 5.  As 3/4
//  HasMany(x => x.Staff).Cascade.None();                       // 6. As 1/2

// Exception of 1) 
// On StoreRepositorySaveOrUpdate(stores): TransientObjectException: 
// object references an unsaved transient instance - save the transient instance before flushing. 
// Type: FNHib_Test.Entities.Employee, Entity: FNHib_Test.Entities.Employee

// Exception of 3) 
// On EmployeeRepository.Delete(employee);    transaction.Commit()
// ObjectDeletedException was unhandled: 
// deleted object would be re-saved by cascade 
// (remove deleted object from associations)[FNHib_Test.Entities.Employee#1]

EDIT5:

Findings to above exceptions:

1) Store is aggregate root ( No Inverse set). Since no cascade: I need to handle added children manually on saving aggregate. (OK)

2) Employee is aggregate root (Inverse set). Still, since no cascade: I need to handle added Employee manually, simply because the stores collection contain both persistent and transient entities. So the clue of 1 and 2 is simply that cascade = none. Inverse is irrelevant. (OK)

3) Store is aggregate root (No inverse set). Cascade=all, and it works in both directions, not only from the aggregate root? So we can not delete the child without first removing it’s reference to the parent. (Maybe OK).

4) Same reason as 3. Inverse makes no difference on the cascade. (Maybe OK)

5) Same reason as 3.

6) Same as 1.

If this is the conclusion. Then it means we are forced to remove the reference between bidirectional entities before delete of child. No matter the setting of Inverse.

So: I can’t see that Inverse has ANY effect on a bidirectional relationship. ?


EDIT6:

(breathe..) Even setting the emp.Store = null; It still gives ObjectDeletedException:
deleted object would be re-saved by cascade (remove deleted object from associations)[FNHib_Test.Entities.Employee#1]

This was with mapping; HasMany(x => x.Staff).Cascade.All();

    public static void Delete(Employee employee)
    {
        using (ISession session = FNH_Manager.OpenSession())
        {
            using (ITransaction transaction = session.BeginTransaction())
            {
                employee.Store = null;
                if (employee.Id != 0) 
                { 
                  // var emp =  session.Get(typeof(Employee), employee.Id);
                  Employee emp = session.Get<Employee>( employee.Id);
                  if (emp != null)
                  {
                    emp.Store = null;
                    session.Delete(emp);
                    transaction.Commit();
                  } 
                }
            }
        }
    } 

I wonder if there can be a problem related to the entity-Id’s not being set when I save transient instances. This is why I Load after each Save. But I don’t know why they are not set. As I described here: NHibernate: How is identity Id updated when saving a transient instance?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T01:07:39+00:00Added an answer on May 20, 2026 at 1:07 am

    Ok.. Finally.. I found at least a working solution. Not sure if this is how it’s supposed to be solved though:

    What is required is to delete the instance from the parent list. The child can still have reference to the parent, but not other way around. So, as shown below:

    emp.Store.Staff.Remove(emp);

    It seems a bit awkward. That’s just a normal parent child-relation where we try to delete the child. But maybe someone else can elaborate with proper knowledge…

    Btw, this is with the mapping: HasMany(x => x.Staff).Cascade.All();

        public static void Delete(Employee employee)
        {
            using (ISession session = FNH_Manager.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
    
                    if (employee.Id != 0) 
                    { 
                      Employee emp = session.Get<Employee>(employee.Id);
    
                      if (emp != null)
                      {
                        emp.Store.Staff.Remove(emp);
                        session.Delete(emp);
                        transaction.Commit();
                      } 
                    }
                }
            }
        } 
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

When you have parent-child tables and you wish to use a DetailsView to edit
How can I set parent-child relation on same table? Id int, title string, ParentId
I have a need to close a parent form from within child form from
I notice sometimes with my parent/child objects or many-to-many relationships, I need to call
How do I extend my parent's options array for child classes in PHP? I
I have a parent/child relationship defined which, unfortunately, cannot be maintained via a foreign
I'm using Core Data to store lists of data. So, there's parent objects with
I have mysql error with code 1451. Cannot delete or update a parent row:
I have a parent node and I'm trying to get each child node under
I have a parent object which has a one to many relationship with an

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.