开发者

Does NHibernate override mapped setters?

开发者 https://www.devze.com 2023-02-22 14:35 出处:网络
I would like to do this in an NHibernate mapped object: private ShiftTradeOffer m_Offer; public virtual ShiftTradeOffer Offer{

I would like to do this in an NHibernate mapped object:

    private ShiftTradeOffer m_Offer;

    public virtual ShiftTradeOffer Offer{ 
        get {
            return m_Offer;
        }
        set {

            //... Do some stuff ...

            if (condition)
            {
                m_Offer = value;
            } else {
                throw new Exception("whoops!");
            }

        }
    }

(ShiftTradeOffer being a mapped property)

1) Will this sort of thing pose a problem?

2) Is this setter invoked 开发者_开发问答when the object is created?

3) Is this against best practices, in terms of enforcing validation? I would like to have object-specific behavior embedded in this class.


1) Properties should, by definition, never throw exceptions. Your approach violates this best practice.

2) The original setter is invoked because NHibernate just creates a proxy which calls the underlying getter/setter. We use properties containing serialization logic to map serialized data which would not work otherwise.

Example:

public virtual List<Foo> Foos {get;set;}
public virtual string SerializedFoos 
{
    get { return JsonConvert.Serialize(Foos); }
    set { Foos = JsonConvert.Deserialize<List<Foo>>(value); }
}

Only the SerializedFoos Property is mapped and the domain code works with Foos Properties. So NHibernate writes nice JSON to the database while the domain can work with a handy List without taking a performance hit because (de)serialization only takes place when the object is loaded/saved.

3) There are many practices to validate, some prefer Attributes, some prefer a validation class per domain object.

I would go with the latter one because it's most flexible and you don't mess up your data object and you can easily validate the whole object.

One search term for the attribute way is "data annotations". Google brought up this result for example: http://stephenwalther.com/blog/archive/2008/09/10/asp-net-mvc-tip-43-use-data-annotation-validators.aspx

If you do databinding you may take a look at the IDataErrorInfo interface.

0

精彩评论

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