NHibernate;删除子项也会删除父项吗?

2024-01-04

为什么是当我删除子级(员工)时,父级(商店)也被删除?

我配置为约定 Cascade.All.

The 用户输入序列很简单:

  • 从空数据库开始
  • 添加家长
  • 保存,加载(加载=重新加载完整对象图)
  • 添加一个孩子
  • 保存、加载
  • 删除子项
  • 结果:数据库为空。 (父级已删除)

这可能是一个基本的映射错误,因为这是我第一次使用 NHibernate。我想存储为聚合根,并认为通过not在 Store.Staff 属性上设置 Inverse,则 Store 表将负责保存,从而负责保存聚合根。这是一个误解吗?实际上,无论我是否使用 Inverse,我仍然会得到相同的结果。所以也许 这不是问题,但我也想了解这一点。

并且故意不使用更广泛的会话范围,因为我想学习如何使用分离和瞬态实体。

员工删除方法:

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

}

实体:

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

程序伪代码和生成的“SQL”:

程序启动

加载:商店stores = StoreRepository.GetAll()



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

添加父级:将商店添加到空集合商店

保存: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)]
  

加载: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)]
  

添加子项:到空子集合,针对选定的商店

保存: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)]
  

加载: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)]
  

删除子项:(删除所选商店的员工)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)]
  

加载:stores = StoreRepository.GetAll()



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

(没有结果,数据库为空)


EDIT1:

没有逆向的 SQL

程序启动

加载:商店stores = StoreRepository.GetAll()



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

添加父级:将商店添加到空集合商店

保存: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)]
  

加载: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)]
  

添加子项:到空子集合,针对选定的商店

保存: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)]
  

加载: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)]
  

删除子项:(删除所选商店的员工)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)]
  

加载:stores = StoreRepository.GetAll()



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

(仍然;没有结果,数据库为空)

程序窗口

所选商店的商店集合和子集合绑定到 BindingSource/DataGridView/BindingNavigator,如下所示:


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

我现在已经尝试了下面的所有不同映射(1-6)。如果没有级联约定,我对所有替代方案都会遇到例外。我是吗被迫手动删除引用?我认为不应该被要求。



// 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:

对上述异常情况的调查结果:

1) 存储为聚合根(无逆集)。由于没有级联:我需要在保存聚合时手动处理添加的子项。 (好的)

2)Employee是聚合根(逆集)。尽管如此,由于没有级联:我需要手动处理添加的 Employee,只是因为商店集合包含持久实体和瞬态实体。所以1和2的线索就是cascade = none。反之则无关紧要。 (好的)

3)存储为聚合根(无逆集)。 Cascade=all,而且它是双向工作的,不仅仅是从聚合根开始?因此,如果不首先删除子级对父级的引用,我们就无法删除子级。 (也许OK)。

4)与3相同的原因。逆对级联没有影响。 (也许OK)

5) 原因与3相同。

6) 与 1 相同。

如果这是结论的话。那么这意味着我们被迫在删除子实体之前删除双向实体之间的引用。无论 Inverse 的设置如何。

So: 我看不出 Inverse 对双向关系有任何影响。 ?


EDIT6:

(呼吸..)甚至设置emp.Store = null;它仍然给对象删除异常: 已删除的对象将通过级联重新保存(从关联中删除已删除的对象)[FNHib_Test.Entities.Employee#1]

这是与地图相关的;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();
                  } 
                }
            }
        }
    } 

我想知道在保存瞬态实例时是否存在与未设置实体 ID 相关的问题。这就是为什么我在每次保存后加载。但我不知道为什么它们没有被设置。正如我在这里所描述的:NHibernate:保存临时实例时如何更新身份ID? https://stackoverflow.com/questions/4896001/nhibernate-how-is-identity-id-updated-when-saving-a-transient-instance


不要在您的情况下使用逆映射。无逆应该没问题。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

NHibernate;删除子项也会删除父项吗? 的相关文章

随机推荐