4
votes

I'd like to know, How Could I map (with fluent nhibernate) this model:

public class Category
{
   private IList<Product> _products;
   public IEnumerable<Product> Products {
       get { return _products; }
   }
   /* others properties */   


   public Category() {
       _products = new List<Product>();
   }


   // to add a product i'd use something like this:
   public void AddProducts(Product product) {
      product.Category = this;
      _products.Add(products);
   }
}

Today, I'm using a property of IList, but I don't want to expose the methods like "Add", "Remove", etc... on my property, So I think to expose a simple property of IEnumerable and encapsulate an IList like a private field!

So, Is it a good pratice ? How could I map it using NHibernate?

Thanks

Cheers

2
A little off-topic; but yes, this is good practice (not exposing the collection directly). - DanP

2 Answers

6
votes

If you follow a naming convention that NHibernate can work with, and your sample code does, it's very easy:

HasMany(x => x.Products).KeyColumn("ProductId")
    .AsBag().Inverse()
    .Access.CamelCaseField(Prefix.Underscore);
    // plus cascade options if desired

I think this is more than a good practice, I think it's almost always the right practice.