Fluent NHibernate Cascade Issue - Trying To Insert NULL ID

前端 未结 3 1551
忘掉有多难
忘掉有多难 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.

提交回复
热议问题