保存实体时复制子条目

时间:2011-08-16 23:58:47

标签: c# nhibernate c#-4.0 fluent-nhibernate

我在更新实体时会得到重复的孩子。

提交代码:

Report report = _ReportService.GetReport(id);

report.AddDocument(
    new Document
    {
        Extension = qqfile.Substring(qqfile.Length - 3),
        Path = g.ToString(),
        Type = TypeHelper.GetDocumentType(report.Status),
        User = MemberFactory.MemberInfo
    }
);


report.Status = (ReportStatus)((int)report.Status + 1);

_reportRepository.SaveOrUpdate(report);



public class Document : BaseModel
{
    public virtual string Path { get; set; }
    public virtual string Extension { get; set; }
    public virtual DocumentType Type { get; set; }
    public virtual User User { get; set; }
    public virtual Report Report { get; set; }
}

public class DocumentMap : ClassMap<Document>
{
    public DocumentMap()
    {
        Id(x=> x.Id);
        Map(x=> x.Extension);
        Map(x => x.Path);
        Map(x => x.CreateDate);
        Map(x => x.LastModified);
        Map(x => x.Type).CustomType<int>();

        References<User>(x => x.User);
        References<Report>(x => x.Report);
    }
}

public class Report : BaseModel
{
    public virtual Patient Patient { get; set; }
    public virtual ReportStatus Status { get; set; }
    public virtual DateTime AppointmentStart { get; set; }
    public virtual DateTime AppointmentEnd { get; set; }
    public virtual ReportType Type { get; set; }
    public virtual IList<Document> Documents { get; set; }
    public virtual long Kareo_Id { get; set; }

    public Report() 
    {
        this.Status = ReportStatus.New;
        this.Documents = new List<Document>();
    }

    public virtual void AddDocument(Document document)
    {
        document.Report = this;
        this.Documents.Add(document);
    }
}


public class ReportMap : ClassMap<Report>
{
    public ReportMap()
    {
        Id(x => x.Id);
        Map(x => x.CreateDate);
        Map(x => x.LastModified);
        Map(x => x.AppointmentStart);
        Map(x => x.AppointmentEnd);
        Map(x => x.Type).CustomType<int>();
        Map(x => x.Status).CustomType<int>();
        Map(x => x.Kareo_Id);

        References<Patient>(x => x.Patient);
        HasMany<Document>(x => x.Documents)
            .Inverse()
            .Cascade.All();
    }
}

2 个答案:

答案 0 :(得分:0)

实体的映射我将其作为文档图: 你应该添加

References<User>(x => x.User).Cascade.None();

Cascade.None()将停止级联任何更改。

此外,您还可以使用intellisense为您提供在编写.Cascade时可以使用的选项。

Rev 2
这应该适用于两个映射

  

引用(x =&gt; x.User).Cascade.None();参考文献(x =&gt;   x.Report).Cascade.None();

答案 1 :(得分:0)

尝试将AsSet添加到映射

    HasMany<Document>(x => x.Documents)
        .AsSet()
        .Inverse()
        .Cascade.All();

您需要将IList更改为ICollection并使用System.Collections.Generic.HashSet对其进行初始化。

问题的原因是你可能会将同一个文档添加到列表中两次,因为它没有保存,所以它会被插入两次到db。