Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping a Private Field in NHibernate (with Fluent NH)

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

like image 577
Felipe Oriani Avatar asked Feb 26 '23 15:02

Felipe Oriani


1 Answers

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.

like image 126
Jamie Ide Avatar answered Mar 06 '23 18:03

Jamie Ide