OnSave 在 Castle ActiveRecord 中如何工作?
我是 Castle ActiveRecord 的新手,在保存对象之前更新对象时遇到了一些困难。阅读 doco 后,我期望 OnSave 或 BeforeSave 始终在数据库调用之前更新对象,但情况似乎并非如此。
有时该值已设置,有时则未设置。我已经尝试过 OnSave 和 BeforeSave,从 NH Prof 中我可以看出,有时该值只是 NULL。我尝试过 Flushing、SaveAndFlush、SaveCopy 等,但没有任何变化。
这是我的示例代码:
[ActiveRecord]
public class Blog : ActiveRecordValidationBase<Blog>
{
[PrimaryKey] public int Id { get; set; }
[Property] public DateTime CreatedOn { get; set; }
[Property] public string Name { get; set; }
[Property] public string Author { get; set; }
protected override void OnSave()
{
Author = "Test Author 1";
base.OnSave();
}
}
// in a test:
var blog = new Blog { Name = "First Blog", CreatedOn = DateTime.UtcNow };
blog.Save();
INSERT INTO Blog (
CreatedOn,
Name,
Author
)
VALUES (
'2011-07-25T14:48:06.00' /* @p0 */,
'First Blog' /* @p1 */,
NULL /* @p2 */
)
这是一个刷新问题吗?我是否不理解 OnSave 的工作原理,还是其他原因?我使用的是 Nuget 的 ActiveRecord beta 3.0 版本,这是问题所在吗?任何帮助都会很棒,谢谢。
更新
经过更多查看后,我想我明白了这个问题。当字段不可为空时,插入会失败。但是,如果该字段可为空,则会连续生成单独的插入和更新命令并且它可以工作。
我可以在 OnSave 中使用 ActiveRecord 设置数据库中的非空字段吗?
I am new to Castle ActiveRecord and am having a little difficulty with updating an object before it is saved. After reading the doco I expected OnSave or BeforeSave to always update the object prior to the database call, but that doesn't seem to be the case.
Sometimes the value is set, sometimes it is not. I have tried both OnSave and BeforeSave and from what I can tell looking in NH Prof sometimes the value is just NULL. I have tried Flushing, SaveAndFlush, SaveCopy, etc with no change.
Here's my sample code:
[ActiveRecord]
public class Blog : ActiveRecordValidationBase<Blog>
{
[PrimaryKey] public int Id { get; set; }
[Property] public DateTime CreatedOn { get; set; }
[Property] public string Name { get; set; }
[Property] public string Author { get; set; }
protected override void OnSave()
{
Author = "Test Author 1";
base.OnSave();
}
}
// in a test:
var blog = new Blog { Name = "First Blog", CreatedOn = DateTime.UtcNow };
blog.Save();
INSERT INTO Blog (
CreatedOn,
Name,
Author
)
VALUES (
'2011-07-25T14:48:06.00' /* @p0 */,
'First Blog' /* @p1 */,
NULL /* @p2 */
)
Is this a flushing issue, am I not understanding how OnSave works, or is it something else? I am using the beta 3.0 version of ActiveRecord from Nuget, is that the issue? Any help would be great, thanks.
Update
After looking at this more I think I see the issue. When the field is not nullable it fails on the insert. But if the field is nullable separate Insert and Update commands are generated back to back and it works.
Can I have a non-nullable field in a database be set in OnSave with ActiveRecord?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以重写该
方法并以与 OnSave 类似的方式实现您的逻辑,它应该按您想要的方式工作。
You can override the
method and implement your logic there in a similar way you are doing with OnSave, it should work as you want.