【问题标题】:Custom ormlite query implementation based on class interface基于类接口的自定义ormlite查询实现
【发布时间】:2016-06-17 19:10:44
【问题描述】:

我想根据对象的实现扩展某些 ORMLite 方法。例如,

我有一个界面:

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

现在我想覆盖 Db.Insert<T>() 方法,仅当 T 实现 IHaveTimestamps 并且对于 T 的其他实例,它应该基于默认行为执行 Insert

这样我可以集中设置 CreatedOn 和 UpdatedOn 值,而不是到处手动设置。

我可以通过重载插入/更新方法来做到这一点,这样我需要做的就是更新模型以从接口继承,所有数据库操作都会自行处理,还是我需要做类似的事情这个:

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);
    }
}

【问题讨论】:

    标签: servicestack ormlite-servicestack


    【解决方案1】:

    看看OrmLite Global Insert/Update Filters,它已经允许你做这样的事情,例如:

    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;
    };
    

    【讨论】:

    • 这太聪明了!
    • @mythz 是否可以将请求对象注入这些过滤器,以便我可以实现由用户/租户 ID 自动过滤的查询
    • @vonec 不,OrmLite 对 ServiceStack 没有任何依赖关系。
    • @mythz 也使用 UpdateOnly 意味着我的应用程序中实现 IAudi 的某些部分仍需要记住手动更新这些字段?
    • @mythz 您可能需要在文档中添加注释,因为如果您使用 UpdateOnly 并且您没有在要更新的字段中指定 ModifiedDate,这将不起作用。
    猜你喜欢
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多