Howto automatically fill fields during save or update with Castle ActiveRecord

左心房为你撑大大i 提交于 2019-12-05 17:43:20

To modify data as you you want you have to override the BeforeSave method like this:

    protected override bool BeforeSave(IDictionary state)
    {
        bool retval = base.BeforeSave(state);
        state["Password"] = Global.Encrypt("password");
        return retval;
    }

And finally save your instance:

protected void btnSave_Click(object sender, EventArgs e)
{
    try
    {
        qfh.User user = null;

        user = new qfh.User();

        user.UserName = txtUserName.Text;
        user.Name = txtName.Text;
        user.IsAdministrator = cboIsAdministrador.SelectedValue == "Yes";
        user.IsActive = cboIsActive.SelectedValue == "Yes";

        user.SaveCopy();
    }
    catch (Exception ex)
    {
        ex = Utilities.GetInnerException(ex);
        JSLiteral.Text = Utilities.GetFormattedExceptionMessage(ex);
    }
}

I usually use SaveCopy() to make use of the overriden method FindDirty(object id, IDictionary previousState, IDictionary currentState, NHibernate.Type.IType[] types) to get the previous values of the class.

Hope it helps.

Use BeforeSave() for saving and OnFlushDirty() for updating.

you could do like this

[ActiveRecord("PostTable")]
public class Post : ActiveRecordBase<Post>
{
     private int _id;
     private DateTime _created;

     [PrimaryKey]
     public int Id
     {
        get { return _id; }
        set { _id = value; }
     }

     [Property("created")]
     public DateTime Created
     {
        get { return _created; }
        set { _created = value; }
     }

     private void BeforeUpdate()
     {
        // code that run before update
        Created = DateTime.Now;
     }

    public override void Update()
    {
        BeforeUpdate();
        base.Update();            
    }

I had a same problem and solved it this way:

I use OnUpdate() and OnSave(). As you mentioned this solution does not work with master detail scenarios. For this I set parent of each child explicitly. Note following codes:

[ActiveRecord(Lazy = true)]
public class Lookup : ActiveRecordBase<Lookup>
{
    [HasMany(typeof(LookupItem), Cascade = ManyRelationCascadeEnum.All)]
    public virtual IList Items { set; get; }

    //other properties...
}


[ActiveRecord(Lazy = true)]
public class LookupItem : ActiveRecordBase<LookupItem>
{
    [BelongsTo("Lookup_id")]
    public virtual Lookup ContainerLookup { set; get; }

    //other properties...
}

void SaveLookup()
{
    Lookup lookup = GetLookup();
    LookupItem lookupItem = new LookupItem()
    {
        Title = LookupItemName,
        ContainerLookup = lookup
    };
    lookup.Items.Add(lookupItem);
    lookup.Save();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!