NHibernate : map to fields or properties?

后端 未结 7 1187
傲寒
傲寒 2021-01-02 00:55

When you create your mapping files, do you map your properties to fields or properties :



        
相关标签:
7条回答
  • 2021-01-02 01:34

    I map to properties, I haven't come across the situation where I would map to a field... and when I have I augment my B.O. design for the need. I think it allows for better architecture.

    0 讨论(0)
  • 2021-01-02 01:38

    Null Objects

    Mapping to fields can be useful if you are implementing the null object pattern if your classes. As this cannot be performed (easily) when mapping to Properties. You end up having to store fake objects in the database.

    HQL

    I was unsure that with HQL queries you had to change the property names if you were using a field access approach. ie if you had <property name="FirstName" access="field.camelcase" /> I thought you could still write "From Person where FirstName = :name"; as it would use the property name still.

    Further discussion on field strategies and Null object can be found here.

    Performance

    In relation to performance of field vs property on John Chapman's blog It appears there isn't much of an issue in performance with small-midrange result sets.

    In summary, each approach has certain perks that may be useful depending on the scenario (field access allows readonly getters, no need for setters, property access works when nothing special is required from your poco and seems to be the defacto approach. etc)

    0 讨论(0)
  • 2021-01-02 01:40

    Properties are also useful in the case you need to do something funky with the data as it comes in and out of persistant storage. This should generally be avoided, but some rare business cases or legacy support sometimes calls for this.

    (Just remember that if you somehow transform the data when it comes back out with the getter, NHibernate will (by default) use the return from the getter and save it that way back to the database when the Session is flushed/closed. Make sure that is what you want.)

    0 讨论(0)
  • 2021-01-02 01:41

    I map to properties. If I find it necessary, I map the SETTER to a field. (usually via something like "access=field.camelcase").

    This lets me have nice looking Queries, e.g. "from People Where FirstName = 'John'" instead of something like "from People Where firstName/_firstName" and also avoid setter logic when hydrating my entities.

    0 讨论(0)
  • 2021-01-02 01:41

    I map to properties because I use automatic properties.

    Except for collections (like sets. Those I map to fields (access="field.camelcase-underscore") because I don't have public properties exposing them, but methods.

    0 讨论(0)
  • I map directly to fields, which allows me to use the property setters to keep track of a property's dirty state.

    0 讨论(0)
提交回复
热议问题