Community blog feed
Castle ActiveRecord - Using an identity/computed/default column
- Blog
- The Darkside
- Posted
- 23 Oct 2008 at 08:08
Summary
To expand on the title a bit: What if I have an identity column in a table, but it isn’t my primary key? Or what if I have a computed column or default value for a column, and need to use the value as soon as I’ve created/saved/updated?Firstly, you need to make sure that ActiveRecord doesn’t update
Post extract
To expand on the title a bit: What if I have an identity column in a table, but it isn’t my primary key? Or what if I have a computed column or default value for a column, and need to use the value as soon as I’ve created/saved/updated?
Firstly, you need to make sure that ActiveRecord doesn’t update or insert any values for this column. In my example, I've created an Invoice class/table which has a Guid as the primary, and makes use of a column named Reference which is in fact an identity column in the database table.
[Property(Column = "Reference", Insert = false, Update = false)]
public int Reference { get; set; }
Next, you need to override the "PostFlush" method of your class, in which we check to see if the record needs to be refreshed. Here is the entire working (watered down) class:
[ActiveRecord]
public class Invoice : ActiveRecordBase<Invoice>
{
[PrimaryKey(PrimaryKeyType.GuidComb, Column = "InvoiceId")]
public Guid Id { get; set; }
[Property(Column = "Reference", Insert = false, Update = false)]
public int Reference { get; set; }
protected override void PostFlush()
{
base.PostFlush();
if (this.Reference == 0)
{
using (new SessionScope(FlushAction.Never))
Refresh();
}
}
}
You'll notice that I create a new session scope with the flushaction set to never; this is to prevent (a) the PostFlush from being fired twice on your current object and (2) stops a "System.InvalidOperationException: Collection was modified; enumeration operation may not execute" exception from being thrown if your class is in a collection of child objects belonging to another ActiveRecord class.
Related blog entries
-
Castle ActiveRecord - Lazy Loading and session scopes in the web
by The Darksider
-
Castle ActiveRecord - more on Lazy Loading and session scopes
by The Darksider
-
Generator Studio released on CodePlex
by The Darksider
-
Castle ActiveRecord - Using CreateSchema()
by The Darksider
-
Castle ActiveRecord and Linq
by Ryan Schreiber