NHibernate: adding an entity to the many-to-many collection by id only

I am looking for a shortcut. I have some NH objects with many relationships. Something like that:

public class Customer : EntityBase<Customer> { public virtual IList<Category> Categories { get; set; } } public class Category : EntityBase<Category> { public virtual IList<Customer> Customers { get; set; } } 

Remember that this is a very simple description, so do not be tempted to suggest that I do not use the many-to-many scheme or that I should use a value type or something like that.

On the database side, this relationship is performed through a separate table with two columns - Customer_Id and Category_Id .

I would really like to add an existing Category to Customer without having to retrieve the complete object from the database. Maybe something like this:

 customerEntity.Categories.Add(new Category { Id = 2 }); 

The reason for this is because the application is an ASP.NET MVC application, and I use ViewModels for my views. These Customer ViewModels end with a List<int> to select a category, and when I move on to display this ViewModel in the corresponding Customer object, I would like to simply suck these category identifiers in Categories without having to delete the database to get them first.

Partially, I want this to be possible, that I would like to minimize database calls, but I would also like my mapping class to be able to create a Customer object without having to make calls to my service level to request other objects. .. which seems like a bad design. I would also like to avoid having to add another layer to call mapper, and then make another mapping material that pulls objects from the repository (which it accesses through the domain service level).

I checked idbag , but for one I use Fluent NHibernate, and it does not support this construct, and for two, what I can extract from documents that will give me a List<int> for the object, and I would still like to have access to the full essence in these collections.

Am I asking too much about NHibernate?

+4
source share
1 answer

Use ISession.Load :

 customerEntity.Categories.Add(session.Load<Category>(2)); 

The download returns a proxy server and does not get into the database. You can access the proxy ID property without getting into the database, but NHibernate will load the proxy if you get access to other properties.

+3
source

All Articles