userbb
userbb

Reputation: 1874

Unique names in primary keys

I have db tables in each I have same primary column name ('ID')

I get error from nhibernate:

System.IndexOutOfRangeException : An SqlCeParameter with
ParameterIndex '5' is not contained by this SqlCeParameterCollection

When I change these columns names to unique names, all is ok.

But i wonder how to fix it without name changes. I simply want same name in each table.

 <class name="AppSignature" table="app_signatures" lazy="true">
    <id name="Id"><generator class="guid"></generator></id>

  </class>

  <class name="AppState" table="app_states" lazy="true">
    <id name="Id"><generator class="guid"></generator></id>

    <many-to-one name="app_signature" 
                 class="AppSignature"                 
                 column="Id"
                 foreign-key="id_fom_app_signature"
                 not-null="true"                 
                 >         
    </many-to-one>

  </class>

Upvotes: 1

Views: 316

Answers (1)

Jakub Linhart
Jakub Linhart

Reputation: 4072

Many-to-one relation means that an AppState instance can be assigned at most to one AppSignature instance. To an AppSignature can be assigned any number of AppState instances. This relation is implemented as an foreign key from app_states table to app_signatures table. "Column" attribute in "many-to-one" element determines column name that stores a value for the foreign key. To the Id column are mapped two AppState members: Id and app_signature which is not possible in NH and leads to the described exception. The fix is easy:

<many-to-one name="app_signature" 
             class="AppSignature"                 
             column="app_signature_id"
             foreign-key="id_fom_app_signature"
             not-null="true"                 
             >         
</many-to-one>

Name of column that implements foreign key was changed to an unique name: "app_signature_id". Now app_signature member is mapped to AppState.app_signature_id column which points to the app_signatures.Id column

However described exception should disappear (if the new column is properly added to app_signatures table) it would not necessarily be what you you really want. The relation between AppState and AppSignature could be one-to-one. It means an AppState instnace can be assigned to a single AppSignature instnance and vice versa. Such relation could be implemented by a primary and foreign key on the same column. There is a very nice article about one-to-one relations.

Upvotes: 2

Related Questions