Search code examples
fluent-nhibernateautomapping

fluent nhibernate: INSERT error when saving a new entity with a child entity


I am trying to save a new entity 'Post' with 1 item added to its 'Revisions' List.

A Post can have many PostRevisions, and a PostRevision can only have one Post.

I have tried several ways of mapping the PostRevisions, my PostRevisionMap is as follows:

 public PostRevisionMap()
    {
        Id(x => x.PostRevisionId, "PostRevisionId");
        Map(x => x.Created, "CreateDateTime").Not.Nullable();
       /// SOME OTHER STUFF HERE
        References(x => x.Post, "PostId"); // OPTION 1

        References(x => x.Post,"PostId").ForeignKey("PostId").PropertyRef(d => d.PostId);  // OPTION 2

        HasOne<Post>(x => x.Post).ForeignKey("PostId").Cascade.All().PropertyRef(x => x.PostId); // OPTION 3
    }

When calling SaveOrUpate I get a different errors

OPTION 1 & 3 cause

The INSERT statement conflicted with the FOREIGN KEY constraint "PostId".

OPTION 2 causes

NHibernate.HibernateException : Unable to resolve property: PostId

My PostMap is as follows:

   public PostMap()
    {
        Id(x => x.PostId).Column("PostId");

        HasMany(x => x.Revisions)
            .Cascade.All()
            .Table("PostRevisions")
            .KeyColumn("PostId")
            .ForeignKeyConstraintName("FK_PostRevision_Post");

       /// OTHER STUFF
    }

Can anyone point me in the right direction as I can not spot the issue. TIA


Solution

  • Try this:

    PostMap

    HasMany(x => x.Revisions)
        .Inverse()
        .Cascade.All();
    

    PostRevisionMap:

    References(x => x.Post);