Fluent nHibernate, Auto-Incrementing Numeric other than a Key
I have a situation where say, a Notebook
stores Pages
. At first, I had it structured like this.
class Notebook
{
// ...
public virtual IList<Page> Pages
{
get;
set;
}
}
class Page
{
// ..
public virtual int Number
{
get;
set;
}
}
That worked okay. Each page had a page number. I would have the ability to re-order pages in my UI, and update the number. No problem. Then I discovered I could use a Dictionary, and simplify it more...
class Notebook
{
// ...
public virtual IDictionary<int, Page> Pages
{
get;
set;
}
}
class Page
{
// ..
}
And map it like so..
public class NotebookMap : ClassMap<Notebook>
{
public NotebookMap()
{
// Specify the Entity Primary Key
Id(x => x.Id);
// one notebook wil开发者_高级运维l have a list of pages with page numbers
HasMany<int, Page>(x => x.Pages)
.DictionaryKey<int>("Number")
.DictionaryValue<Page>("Page")
.ForeignKey("Notebook")
.Schema("Notebook").Table("Pages");
Schema(Schemas.Collections ); Table("Notebooks");
}
}
Huzzah, everything was right with the world. This works great. But I'm curious...
Is there any way to bind Number
to something that will make sure to auto-increment per Notebook
? Right now, I just handle this in my Service
by using the Notebook.Pages.Count
method when I add a new page. But fluent nHibernate seems pretty smart. Is there any way I can integrate it right into the mapping, so that anytime I add a new page, it just gets the count and makes sure the number is appropriate?
I think you really want to keep this out of the mapping. You'd be mixing the application logic (Where should the next page go) with the model (how am I storing the next page). Also if you make this column auto-increment you'd have to do it on a per table basis. Unless you are creating a new table for each book, you'd (AFAIK) only be able to have 1 consistently incrementing key (as the native generator which uses auto increment columns in NHibernate is done via the database).
精彩评论