Reputation: 6005
I'm looking for a shortcut. I have some NH entities with a many-to-many relationship. Something like this:
public class Customer : EntityBase<Customer>
{
public virtual IList<Category> Categories { get; set; }
}
public class Category : EntityBase<Category>
{
public virtual IList<Customer> Customers { get; set; }
}
Bear in mind this is a very simple depiction, so resist the temptation to suggest I not use a many-to-many arrangement or that I should use a value type or anything like that.
On the DB side, this relationship is accomplished via a separate table with two columns - Customer_Id
and Category_Id
.
I'd really like to be able to add an existing Category
to a Customer
without having to retrieve the full entity from the database. Maybe something like this:
customerEntity.Categories.Add(new Category { Id = 2 });
The reason for this is that the application is an ASP.NET MVC app and I'm using ViewModels for my views. These Customer
ViewModels end up with a List<int>
for the category selections, and when I go to map that ViewModel to the corresponding Customer
entity, I'd love to just be able to suck those category IDs into the Categories
list without having to hit the database to retrieve them first.
Part of the reason I want to be able to do this is that I'd like to minimize database calls, but I also would like to have my mapper class be able to create the Customer
entity without having to make calls to my service layer to go asking for other objects...that seems like bad design. I'd also like to avoid having to add another layer to call the mapper then do the other mapping stuff that pulls entities from the repository (which is itself accessed through a domain service layer).
I checked out idbag
, but for one I'm using Fluent NHibernate and it doesn't support that construct, and for two from what I can glean from the docs that will give me a List<int>
on the entity, and I'd still like to be able to access the full entity in those collections.
Am I asking too much out of NHibernate?
Upvotes: 4
Views: 865
Reputation: 49261
Use ISession.Load:
customerEntity.Categories.Add(session.Load<Category>(2));
Load will return a proxy and does not hit the database. You can access the ID property of the proxy without hitting the database, but NHibernate will load the proxy if you access any other properties.
Upvotes: 3