I am inserting a record into my table, but I want to be able to set my
SortOrder field on insert to SELECT MAX(SortOrder) + 1 FROM Category
WHERE SiteID = @SiteID. What is the easiest way of doing this?
Here is my data structure:
Category
ID
SiteID
SortOrder
Name
I am using Fluent NHibernate and Linq to NHibernate. Thanks for any help!
Ok, here are 2 ways. The simplest may not involve NHibernate since you’re using SQL Server… You could just create an INSTEAD OF INSERT trigger on your table, like so:
In this first scenario you would just NHibernate map the SortOrder column as read only (just add a .ReadOnly() on the fluent nhibernate class map SortOrder property).
The second way would be to use NHibernate’s built in feature called interceptors. With an interceptor you can run whatever code you like just at the time when NHibernate would normally generate SQL to execute a DML action. The below auto-inserts creation info but would be very similar to what you would need. IInsertLoggable is a custom interface that simply lists the properties/columns of interest for interception.
In my opinion this sort of classic trigger operation should probably live on the database and I’d go with the first option…