简体   繁体   中英

Why protected set for one to many relationship property

I have Customer and Order entities. While defining the class for customer using fluent hibernate, why do we need to specify "protected set" for Orders list property.

public virtual IList<Order> Orders { get; protected set; }

You are not required to specify protected on setter. It's just a good design to do so.

If no access modifier is specified on setter, it will implicitly have the same access modifier as the property itself ( public in your case). When setter is public, any consumer of your class could modify the Orders property and set it to another instance.

public class Customer
{
    public virtual IList<Order> Orders { get; set; }
}

var customer = new Customer();
customer.Orders = new List<Order>();

When you define protected access modifier on setter, only the inherited class will be able to modify the property. To any other consumers, the Orders property appears as read-only. This is effectively an encapsulation .

NHibernate uses lazy-loading by default. It's a technique where some properties (usually lists) are not loaded immediately, but on the first usage. NHibernate implements this with proxies. A proxy class, which is dynamically created, inherits from your Entity class and overrides all of it's properties. That's the reason you have virtual on all your class members.

And, to get to the point, when you define protected set you are allowing NHibernate's dynamic proxy to modify your Orders property. Orders could be initialized to some empty proxy collection and when someone tries to read it, a database load will be triggered and Orders property will be replaced with a list of Order instances loaded from the database.

public class Customer
{
    public virtual IList<Order> Orders { get; protected set; }
}

var customer = new Customer();
//customer.Orders = new List<Order>(); // error: can't modify property

var orderCount = customer.Orders.Count; // this will trigger lazy-loading

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM