C# 如何用Castle ActiveRecord实现CreatedAt属性
假设我想创建一个名为EntityWithCreatedAt的类:C# 如何用Castle ActiveRecord实现CreatedAt属性,c#,castle-activerecord,C#,Castle Activerecord,假设我想创建一个名为EntityWithCreatedAt的类: class Entity<T> : ActiveRecordBase<T> { [PrimaryKey] public int Id { get; set; } } class EntityWithCreatedAt<T> : Entity<T> { [Property] public DateTime CreatedAt { get; set; } } 类实体:
class Entity<T> : ActiveRecordBase<T>
{
[PrimaryKey]
public int Id { get; set; }
}
class EntityWithCreatedAt<T> : Entity<T>
{
[Property]
public DateTime CreatedAt { get; set; }
}
类实体:ActiveRecordBase
{
[主密钥]
公共int Id{get;set;}
}
类EntityWithCreatedAt:Entity
{
[物业]
public DateTime CreatedAt{get;set;}
}
填充CreatedAt字段的最佳方式是什么?我是用CreateDat的构造函数在Entity中实现它,还是有其他方法
那么UpdatedAt属性呢
谢谢,在Rails的AR实现中,CreatedAt和UpdatedAt是在迁移中创建的自动时间戳(尽管您也可以手动创建它们)。假设您想要相同的行为,则需要覆盖创建和更新
public override void Update()
{
UpdatedAt = DateTime.Now;
base.Update();
}
public override void Create()
{
CreatedAt = DateTime.Now;
base.Create();
}
如果您没有使用指定的主键,并且DB正在为您生成它(例如,使用自动递增),那么您可能正在使用Save方法来决定是调用Create还是Update。使用Save仍然可以很好地为您服务,因为对基类的Save()方法的调用将触发对Create(如果尚未设置ID)或Update(如果已设置ID且记录以前已保存)的调用
这种方法唯一的缺点是CreatedAt和UpdatedAt属性应该始终反映数据库中保存的内容,但在您的情况下,您是在知道提交到数据库成功之前设置属性的。这是不可避免的,但是在更新覆盖中使用一些try/catch代码,您应该能够记录以前的值,并在出现任何错误时将其分配回:
public override void Update()
{
DateTime originalUpdatedAt = UpdatedAt;
try
{
UpdatedAt = DateTime.UtcNow; // Assuming you're using UTC timestamps (which I'd recommend)
base.Update();
}
catch // Don't worry, you're rethrowing so nothing will get swallowed here.
{
UpdatedAt = originalUpdatedAt;
throw;
}
}