Castle ActiveRecord and Fluent Create/Update/Save

I came up with an interesting idea the other day at work involving some work I had been doing with Castle ActiveRecord. I am using (a modified) GeneratorStudio to produce ActiveRecord partial classes based on a database schema that I have. All of my code additions go into another set of partial class files so that I can regenerate the base classes whenever I need to.

However, there are many times when I need to find a specific item, and if it isn’t found, I need to create a new one. After this, it is used for yet another item. So essentially, the item has to exist before the code can continue. This is where my slightly clever (if I can call it that) idea comes into play.

I will be using part of the example Post class from http://www.castleproject.org/ActiveRecord/gettingstarted/classes.html as a basis for the new idea:

[ActiveRecord]
public class Post : ActiveRecordBase<Post>
{
    private int id;
    private String title;
 
    public Post()
    {
        created = DateTime.Now;
    }
 
    [PrimaryKey]
    public int Id
    {
        get { return id; }
        set { id = value; }
    }
 
    [Property]
    public String Title
    {
        get { return title; }
        set { title = value; }
    }
}

For all of my unique indexes, I create additional static helper methods that allow retrieval by those constraints. Let us assume that Title is a unique index; that is, there can only be a single post with a specific title. Then the following function becomes valid (in the Post class):

public static Post GetByTitle(string title)
{
    return FindOne(Restrictions.Eq("Title",title));
}

And here is my little idea for making a small fluent addition (to the Post class):

public Post CreateFluent()
{
    Create();
    return this;
}

A function similar to this would hopefully work for CreateAndFlush, Update, UpdateAndFlush, Save, and SaveAndFlush as well. Once all of this is in place, I now have many new options for dealing with items that need to exist or be updated before they can be used. I find the fluent-like style of this to be easy to read while working through code:

var post = Post.GetByTitle("42") ?? new Post { Title = "42" }.CreateFluent();
 
// do something important with post

Since Post.GetByTitle(string title) will return null if the post cannot be found, the null coalescing operator (??) takes care of automatically running the second half and creating the new Post if a Post with the specified title couldn’t be found. I’m still testing this fully to see how well it works, but I’ll update here once I get concrete evidence of its functionality.

EDIT: I’ve been using this for the last few weeks and I have not run into any issues with it. It looks pretty slick in the code, too.

Leave a Reply

Please be polite and on topic. Your e-mail will never be published.