inutan
inutan

Reputation: 10888

Fluent Nhibernate - HasMany - child objects not saved

I have a ReportRequest object defined as:

public class ReportRequest
{
    public virtual Int32? Id { get; set; }
    public virtual string Description { get; set; }
    public virtual IList<ReportClient> ReportClients{get;set;}
}

and ReportClient is defined as:

public class ReportClient
{
    public virtual int? Id { get; set; }

    public virtual long? ClientId { get; set; }

    public virtual string Name { get; set; }

    public virtual string EmailAddress { get; set; }

    public virtual IList<ReportClient> ChildClients { get; set; }
}

mapping for ReportClient:

public class ReportClientMap : ClassMap<ReportClient>
{
    public ReportClientMap()
    {
        Id(x => x.Id).UnsavedValue(null).GeneratedBy.Native();
        Map(x => x.ClientId);
        Map(x => x.Name);
        Map(x => x.EmailAddress).Length(255);
        HasMany<ReportClient>(x => x.ChildClients)
            .KeyColumn("ParentId")
            .KeyNullable()
            .AsBag()
            .Inverse()
            .ForeignKeyConstraintName("FK_ReportClient_ParentId");
    }
}

ChildClients are required to be saved as ReportClient but with ParentId being set.

Though ReportRequest and ReportClients are being saved fine, but the issue I am facing is ReportClient.ChildClients are not being saved.

I am not even getting any error.

Any ideas?

Upvotes: 2

Views: 4044

Answers (1)

Sly
Sly

Reputation: 15217

You need to set cascade to save-update for ChildClients property mapping:

  HasMany<ReportClient>(x => x.ChildClients)
        .KeyColumn("ParentId")
        .KeyNullable()
        .AsBag()
        .Inverse()
        .Cascade.SaveUpdate()
        .ForeignKeyConstraintName("FK_ReportClient_ParentId");

Upvotes: 7

Related Questions