Wessel Kranenborg
Wessel Kranenborg

Reputation: 1440

Why is NHibernate creating a table without primary key?

We create the database using the schemaExport class of nHibernate. I now have an class with attributes from which we generated the nhibernate mapping. A part of this class is:

public class PluginInstance
{
    ...
    [Bag(2, Name = "RouteParams", Access = "property", Table = "CMS_PluginInstanceRouteParams")]
    [Key(3, Column = "ParamId")]
    [Element(4, Column = "Param", Type = "string")]
    public virtual IList<String> RouteParams
    {
        get { return _routeParamsField; }
        set { _routeParamsField = value; }
    }
    ...
}

The generated part of the nHibernate mapping is the following

<bag name="RouteParams" access="property" table="CMS_PluginInstanceRouteParams">
  <key column="ParamId" />
  <element column="Param" type="string" />
</bag>

For this property is correcty the "CMS_PluginInstanceRouteParams" table created when we call:

var schemaExport = new SchemaExport(configuration);
schemaExport.Create(false, true);

But I was wondering why this table does not have an primary key. The generated structure is database structure

The column ParamId is correctly an foreign key to the table of the class PluginInstance and in the column Param are correctly the values of the property RouteParams stored.

Is there no need for an primary key on this table? Is it possible to set the primary key on this property using the NHibernate.Mapping.Attributes?

Upvotes: 1

Views: 670

Answers (1)

Florian Lim
Florian Lim

Reputation: 5362

The table is not mapped as an entity and as such will never be fetched from the database by itself, therefore NHibernate does not need and will not create a primary key for that table.

Edit:

If you want to have a primary key in that table I suggest adding an extra column for that. Using ParamId as a primary key will not work for you. NHibernate will create the table with a primary key, if you create a class and a corresponding mapping file for RouteParams.

Upvotes: 2

Related Questions