Nhibernate在更新时为子对象添加新条目

时间:2015-05-01 06:55:08

标签: c# nhibernate

 public CaseMap()
        {
            Id(c => c.ID);//.GeneratedBy.Increment();

            Map(c => c.CIN);
            Map(c => c.CaseNumber);
            Map(c => c.Name);
            Map(c => c.RegistryNumber);

            References(c => c.ApplicantType).Column("FK_ApplicantTypeId").Cascade.None();
            References(c => c.ApplicationType).Column("FK_ApplicationTypeId").Cascade.None();
            References(c => c.AVSUser).Column("FK_UserId").Cascade.None();
            References(x => x.Program).Column("FK_ProgramId").Cascade.None(); 

            References(c => c.CaseApplicant).Column("FK_CaseApplicantId").Cascade.SaveUpdate();
            References(c => c.Address).Column("FK_AddressId").Cascade.SaveUpdate();
            References(x => x.Spouse).Column("FK_SpouseId").Cascade.SaveUpdate();


            Map(c => c.SpouseLink);
            Map(c => c.Status);
            Map(c => c.CreatedDate);
            Map(c => c.UpdatedDate);
            Map(c => c.IsArchived);



            Table("tbl_Case");
        }

更新方法 -

 public bool Update(T persistableEntity)
        {
            if (persistableEntity != null)
            {
                session.BeginTransaction();
                session.Update(persistableEntity);
                session.Transaction.Commit();
                return true;
            }
            return false;
        }

更新调用更新了Case表,但为CaseApplicant,Address和Spouse等子对象添加了新条目。

1 个答案:

答案 0 :(得分:0)

存在代码错误

而不是

 cCase.Address = new CaseAddress();
         cCase.Address.Street = record.ResidenceStreet;

应该只是

cCase.Address.Street = record.ResidenceStreet;

cCase.Address = new CaseAddress()在新条目中为CaseAddress结果创建了一个新对象。

此外,更新方法应为session.Merge而不是update

public bool Update(T persistableEntity)
        {
            if (persistableEntity != null)
            {
                session.BeginTransaction();
                session.Merge(persistableEntity);
                session.Transaction.Commit();
                return true;
            }
            return false;
        }