开发者

Possible to set a tempory ignore on a field in nhibernate(so it won't update that field on commit)

开发者 https://www.devze.com 2023-03-10 21:04 出处:网络
I am wondering when I get my object back(Lets say File) and I make these modifications to it. File.Name = \"test\";

I am wondering when I get my object back(Lets say File) and I make these modifications to it.

File.Name = "test";
File.Id = 1;
File.Date = "6/3/2011 12:00:00 am";
File.IsLocked = false

so I get back this file object but Date is not in local time. So when I get it back I right away convert it to local time.

I do this right away(in the same repo method) as this should always be at this point this date should be in local time. I could convert it at a different point what would solve my problem but then the programmer always has to remember once they a File object back they would have to manually call the convertToLocalTime() method.

From past experiences this ended badly with many times it was forgotten to convert to local time. So I really want to leave it there.

So my problem is this

the File now looks like this once returned

File.Name = "test";开发者_运维问答
    File.Id = 1;
    File.Date = "6/3/2011 5:00:00pm";
    File.IsLocked = false

Now I have to take this object and change File.IsLocked To True

File.Name = "test";
    File.Id = 1;
    File.Date = "6/3/2011 5:00:00pm";
    File.IsLocked = true

Now the problem is I need to save this but I don't want to save the local time. I want to ignore this for this one commit(there maybe other times when the Date needs to be saved but not in this instance)

Can I somehow tell nhibernate to not save the converted date?


If you use an interceptor class you can call convertToLocalTime() without let the programmer have to!

public class TestInterceptor
  : EmptyInterceptor, IInterceptor
{
    private readonly IInterceptor innerInterceptor;

    public TestInterceptor(IInterceptor innerInterceptor)
    {
        this.innerInterceptor = this.innerInterceptor ?? new EmptyInterceptor();
    }


 public override bool OnSave(object entity, 
                                object id, 
    object[] state, 
    string[] propertyNames, 
    IType[] types)
    {
        if ( entity is yourType) {
            //call convertToLocalTime()
        }
        return this.innerInterceptor.OnSave(entityName, id,state,propertyNames,types);
    }


}

hth

updated

Interceptors are classes allows you to override base nhibernate methods like OnSave, OnLoad... that are called for every entity.

Look here:

Implementing NHibernate Interceptors

and you can configure it fluently:

return Fluently.Configure()
           ...
            .ExposeConfiguration(c =>{c.Interceptor = new TestInterceptor(c.Interceptor ?? new EmptyInterceptor());})
            ...
            .BuildConfiguration();
0

精彩评论

暂无评论...
验证码 换一张
取 消