1
votes

I have generate some fluent NHibernate code. It has entity code like:

    private ISet<CardPlace> _cardPlace;

    public MagazineType()
    {
        _cardPlace = new HashedSet<CardPlace>();
    }

    public virtual ISet<CardPlace> CardPlace
    {
        get { return _cardPlace; }
        set { _cardPlace = value; }
    }

And mapping for this property like:

       HasMany(x => x.CardPlace)
            .Access.CamelCaseField(Prefix.Underscore)
            .Cascade.AllDeleteOrphan()
            .Fetch.Select()
            .AsSet()
            .Inverse()
            .LazyLoad()
            .KeyColumns.Add("MAGAZINE_ID");

What I don't understand is the .Access.CamelCaseField(Prefix.Underscore) line. Why is it not being mapped directly to property but instead mapped to the private backing field ? Is there any reason for doing this ?

2

2 Answers

2
votes

If you remove the

.Access.CamelCaseField(Prefix.Underscore)

the mapping will be to the property getter and setter.

That line is instructing fluent nhiberate to use the field instead.

1
votes

The answer here would/should/could be: to improve the Domain Model design. The main helper word here would be "encapsulation". Because:

Why are we trying to create our solid model (with all the business/validation rules)...
... while keeping the back door opened, i.e. having public setters.

There is a really nice article, going really deep into that:

Strengthening your domain: Avoiding setters

Let me cite, just from its Summary (but please go through that text)

Aggregate root boundaries are fun to talk about in theory, but many domain models you might look at only have boundaries in name only.
If a domain model exposes operations and commands only to also expose bypassing these operations by going straight to property setters, then there really isn’t a boundary at all.
...
The justification for leaving public setters in place is often expressed in terms of “easier testing”. From experience, invalid domain objects are more confusing and harder to test, simply because you can’t know that you’ve set up a context that is actually valid when using your application.

And all the arguments from the article (read it please) condensed in final paragraph:

We can avoid this confusion and likely extra defensive coding by
removing public setters for data that should only be changed through operations and commands executed on our domain model.
Once again, this is what encapsulation is all about. Our model only exposes what is supported, and disallows what is not.

NOTE: Well, I do use public setters, and I do use "excuses" like "it is better for testing...