我的问题是,当我从一对多关系中删除一个对象时,子记录变为孤立而不是删除。我不确定它是否是我设置域模型的方式,或者我在自动映射配置期间没有设置任何内容。评估 - > ShortlistedMentor Relationship是发生孤立记录的地方。它们出现在ShortlistMentor
表和ShortListQuestionResponse
中。我期望的是,当我从关系中删除ShortlistMentor
时,它会从ShortlistMentor表中删除,并且ShortListQuestionResponse表中的条目也会被删除。
public class Appraisal : BaseEntity
{
public Appraisal()
{
ShortlistedMentors = new List<ShortlistedMentor>();
ApprovedMentor = new User();
College = new RefData();
}
#region Primitive Properties
public virtual bool Decision { get; set; }
public virtual System.DateTime? ApprovedDate { get; set; }
public virtual System.DateTime? AcceptedDate { get; set; }
public virtual System.DateTime? CompletionTargetDate { get; set; }
public virtual string RejectionReason { get; set; }
public virtual IList<ShortlistedMentor> ShortlistedMentors { get; set; }
public virtual User ApprovedMentor { get; set; }
public virtual RefData College { get; set; }
}
public class ShortlistedMentor : BaseEntity
{
public virtual User Mentor { get; set; }
public virtual IList<ShortListQuestionResponse> ShortListQuestionResponses { get; set; }
}
public class ShortListQuestionResponse : BaseEntity
{
public virtual string Comment { get; set; }
public virtual int Score { get; set; }
public virtual RefData Question { get; set; }
}
自动地图设置
.Mappings
(
m =>
m.AutoMappings.Add
(
AutoMap.AssemblyOf<User>(cfg)
.Override<Client>(map =>{map.HasManyToMany(x => x.SICCodes).Table("SICRefDataToClient");})
.IgnoreBase<BaseEntity>()
.Conventions.Add(new StringColumnLengthConvention(),new EnumConvention(),DefaultCascade.SaveUpdate())
.Conventions.Add(DefaultLazy.Always())
)
不确定这是否有帮助,但这是我从集合中删除项目并添加新
的方式 ProjectToUpdate.Appraisal.ShortlistedMentors.Clear();
foreach (var userId in Request.Form["ProjectToEdit.Appraisal.ShortlistedMentors"].Split(','))
{
var user = _membershipService.GetUser(Convert.ToInt16(userId));
ProjectToUpdate.Appraisal.ShortlistedMentors.Add(new ShortlistedMentor(){Mentor = user,ShortListQuestionResponses = new List<ShortListQuestionResponse>()});
}
答案 0 :(得分:1)
我认为,由于您的DefaultCascade设置为SaveUpdate(),您需要将HasMany关系(ShortlistedMentors)覆盖为Cascade.AllDeleteOrphan。所以它看起来像这样:
.Override<Appraisal>(map =>{map.HasMany(x => x.ShortlistedMentors).Cascade.AllDeleteOrphan();})
我实际上没有编译它,所以它可能不完美。