I've quite recently discovered NHibernate, so forgive me if this is a beginners question, but I can't find the answer anywhere on Google.
I have three tables, two entity tables and one relation table.
Code:
BlogPosts:
Id Identity (int)
Title (nvarchar)
Content (nvarchar)
Categories
Id Identity (int)
Name (nvarchar)
BlogPostInCategory
Category (int) Foreign key to Categories
BlogPost (int) Foreign key to BlogPosts
These are modeled in C# like this.
Code:
class BlogPost {
public virtual int Id { get; set; }
public virtual string Title { get; set; }
public virtual string Content { get; set; }
public virtual ISet<Category> Categories { get; set; }
}
class Category {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
That displays the relation in code that I want.
I want to be able to select BlogPosts in a certain Category or get all Categories that a certain BlogPost is in.
Category is mapped as an usual entity with Unique key on the Name property.
BlogPost is mapped as usual, but the Categories property is a <set> with <many-to-many> like this.
Code:
<set name="Categories" table="`BlogPostInCategory`" cascade="save-update">
<key column="BlogPost"/>
<many-to-many column="Category"
class="Category, Assembly"/>
</set>
The problem is the following, when doing inserts (I add new Category to the Categories collection) I get exceptions that there already is a Category with that name (Duplicate unique key). How can I tell NHibernate to check before doing insert and if there's a value, it should use that Id instead of trying to insert? This is really bothering me since this isn't a very complex technique. It's just normal normalization and common sense.
I appreciate the help.
Kind regards, Kim Johansson