Fluent NHibernate Cascade Issue - Trying To Insert NULL ID

前端 未结 3 1552
忘掉有多难
忘掉有多难 2021-01-02 00:40

I have the following models & mappings (code snippets further below).

One Competition has to have multiple CompetitionAnswers associated with it (multiple choice

相关标签:
3条回答
  • 2021-01-02 00:51

    I'm pretty sure, not 100%, that the problem is the Inverse() specification in your mapping of CompetitionAnswers on Competition. Inverse() specifies that the child records are responsible for defining their relationship to the parent. Most often, the "one" side of a one-to-many (the parent) is the "top" of an object graph and "owns" the relationship with its children. Parents have children, and the decision regarding whether to keep or give away the child for adoption is the parent's. However, this isn't always the case; a college may have students, but it's the students who have the real power to decide where they will go. Here, the Student is the "top" of the graph, and the School is just a monolithic record identifying the Student's attendance. The Student can transfer at any time; it's their decision, and it doesn't really change the School in any meaningful way, so the Students are responsible for identifying themselves as belonging to the School.

    Your case is the first one: Competitions have CompetitionAnswers, and the child doesn't logically have the responsibility of saying "I belong to a Competition"; the Competition instead "owns" its collection of answers. Removing the Inverse() instruction should make NH treat Competition as the "top" of the object graph, so NH will insert the Competition, then the CompetitionAnswers, which can now reference their parent's ID.

    Another thing not related to the problem, but if you're mapping to an MS SQL Server database, and the ID column is defined as an identity column in the DB, I'd specify GeneratedBy.Identity() for the ID columns. Native() SHOULD end up using Identity, but it will also check to see if HiLo or Sequence methods are available.

    0 讨论(0)
  • 2021-01-02 01:05

    There is nothing wrong with your mappings. The problem is likely with your database. If you're using Identity columns for your primary keys, the CompetitionId column should be set to nullable. The way NHibernate works when you have a brand new object with children that is saved, is it inserts the parent object and the child objects. Then it updates the child object foreign keys with the new parent object id.

    I found this NHibernate cascading save

    0 讨论(0)
  • 2021-01-02 01:06
    References(x => x.Competition)
        .Column("CompetitionId")
        .Not.Nullable(); //add this
    

    and also make sure the child points to the parent in addition to the parent holding the child in it's collection. This is required when the parent is inverse.

    a1.Competition = c; 
    

    Was that column non null on database side but mapped as nullable on NH side?

    0 讨论(0)
提交回复
热议问题