Note that there are some explanatory texts on larger screens.

plurals
  1. POPreventing delete/insert when modifying many-to-many relationship with NHibernate
    primarykey
    data
    text
    <p>In my domain model a User is associated with many Places - the relationship is modelled via a UserPlace class and a mapping (with FluentNHibernate) as follows (the User has a collection of UserPlace called <em>Neighbourhood</em>:</p> <pre><code>public class UserMap : ClassMap&lt;User&gt; { HasMany(x =&gt; x.Neighbourhood) .Component(c =&gt; { c.Map(x =&gt; x.IsDefault).Not.Nullable(); c.Map(x =&gt; x.Selected).Not.Nullable().Default("0"); c.References(x =&gt; x.Place).Fetch.Join(); } ).Not.LazyLoad().Cascade.SaveUpdate(); } </code></pre> <p>Whenever I modify any UserPlace entity belonging to a user and then persist the user to the db, <em>all UserPlace rows for that user are deleted and then re-inserted</em>.</p> <p>I assume this is because NHibernate doesn't know how to uniquely identify one of these rows from another. In other words, the component in my mapping doesn't have a key as such.</p> <p>A primary key can be formed by combining the User_id and Place_id columns in the table that stores the relationship between these two entities. How can I set up this key using Fluent? And will this solve the delete-and-re-insert behaviour that I'm seeing?</p> <p><strong>EDIT:</strong> I asked on NHUsers about this and Fabio Maulo suggested using an IdBag. This isn't supported in Fluent NHibernate as far as I can tell - and components don't allow identifiers. How else can I map this many-to-many relationship and prevent the delete-all-reinsert-all issue?</p> <p><strong>EDIT 2:</strong> Here are the tables that NH generate based on my mappings</p> <pre><code>CREATE TABLE [dbo].[User]( [Id] [uniqueidentifier] NOT NULL, --- a bunch of unimportant fields CONSTRAINT [PK__User] PRIMARY KEY CLUSTERED ([Id] ASC)) CREATE TABLE [dbo].[Neighbourhood]( [User_id] [uniqueidentifier] NOT NULL, [IsDefault] [bit] NOT NULL, [Place_id] [int] NOT NULL, [Selected] [bit] NOT NULL) CREATE TABLE [dbo].[Place]( [Id] [int] IDENTITY(1000,1) NOT NULL, --- a bunch of unimportant fields CONSTRAINT [PK_Place] PRIMARY KEY CLUSTERED ([Id] ASC)) </code></pre> <p>There is a FK relationship between User.Id and Neighbourhood.User_Id and between Neighbourhood.Place_id and Place.Id</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload