vonec
vonec

Reputation: 701

Custom ormlite query implementation based on class interface

I'd like to extend certain ORMLite methods based on the object's implementation. E.g.,

I have an interface:

public interface IHaveTimestamps 
{
    DateTime CreatedOn { get; set; }
    DateTime UpdatedOn { get; set; }
}

Now I'd like to override the Db.Insert<T>() method only if T implements IHaveTimestamps and for other instances of T, it should perform the Insert based on the default behaviour.

This is so that I can centralise setting the CreatedOn and UpdatedOn values, rather than doing that manually everywhere.

Can I do this by overloading the Insert/Update method so that all I would need to do is update the models to inherit from the interface and all the DB operations will take care of itself, or would I need to do something like this:

public static class DbExtensions
{
    public static long MyInsert<T> (this IDbConnection dbConn, T obj, bool selectIdentity = false) where T : IHaveTimestamps {
        obj.CreatedOn = DateTime.UtcNow;
        obj.UpdatedOn = DateTime.UtcNow;
        return dbConn.Insert<T>(obj);
    }

    public static long MyUpdate<T> (this IDbConnection dbConn, T obj) where T : IHaveTimestamps {
        obj.UpdatedOn = DateTime.UtcNow;
        return dbConn.Update<T>(obj);
    }
}

Upvotes: 2

Views: 142

Answers (1)

mythz
mythz

Reputation: 143374

Have a look at OrmLite Global Insert/Update Filters which already allows you to do something like this, e.g:

public interface IAudit 
{
    DateTime CreatedDate { get; set; }
    DateTime ModifiedDate { get; set; }
    string ModifiedBy { get; set; }
}

OrmLiteConfig.InsertFilter = (dbCmd, row) => {
    var auditRow = row as IAudit;
    if (auditRow != null)
        auditRow.CreatedDate = auditRow.ModifiedDate = DateTime.UtcNow;
};

OrmLiteConfig.UpdateFilter = (dbCmd, row) => {
    var auditRow = row as IAudit;
    if (auditRow != null)
        auditRow.ModifiedDate = DateTime.UtcNow;
};

Upvotes: 3

Related Questions