NHibernate: Add entity to many-to-many collection by id only - nhibernate

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?

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.

Related

What is the best way to retrieve/save log entries linked to other entities through NHibernate?

Disclaimer: I'm outlining simplified picture to emphasize main point of my question.
The application I'm working on maintains a set of resources. We have a corresponding table and mapped entity in NHibernate. Each resource identified by integer id. Also we have user table and corresponding entity to maintain user profiles.
We need to log user accesses to the application and retrieve access history. For repository class we have to introduce 2 methods:
IEnumerable GetUserLog(User user) to retrieve user access history order by date in descending order and
void WriteLogEntry(User user, Resource resource) to write new entry
I have tried to simply define LogEntry entity as following:
public class LogEntry
{
public virtual User User {get; set;}
public virtual Resource Resource {get; set;}
public virtual DateTime Date {get; set;}
}
and map it using Fluent NHibernate as usually. To retrieve/update log entries we can simply use
Session.Query<LogEntry>().Where(entry => entry.User = currentUser).OrderByDesc(entry => entry.Date)
Session.Save(new LogEntry() {
User = currentUser,
Resource = resource,
Date = DateTime.Now
})
This is the most convenient way to deal with this issue for us.
Problem
The problem is that NHibernate requires id mapping. We have to use composite id here and the only option is to map User, Resource and Date columns because only this combination provides uniqueness. Also in case of composite id we have to override Equals and GetHashCode and all this seems to be overkill for such a simple task. Another problem that lazy loading cannot be used for id fields and it's too much as well. We do not want to load all related Resource entities in advance.
Another possible solution is to define plain class, not entity and then use SetResultTransformer(Transformers.AliasToBean()) to retrieve results. In that case we have to construct queries manually, retrieve related entities manually and this way it's not better in general then dealing with raw connection.
I would like to ask expert opinion because I'm confident people around had similar experience and can help. Thanks in advance.
P.S. This is ASP.NET MVC application using NHibernate 3 (+ Fluent). Log information will be used to display last 5-10 resources user accessed.
have you considered introducing an Id field for LogEntry table as well?
many DBAs will recommend it and it seems like the easiest solution.

One to one self reference with Fluent NHibernate

Okay, I think I have a scenario I haven't seen elsewhere. I have a situation where I have an object type that needs to be able to be changed over time while retaining the history of the changes within the same table (as opposed to just in an audit table).
public class Item
{
public virtual int Id { get; set; }
public virtual ....
public virtual Item Replaces { get; set; }
public virtual Item ReplacedBy { get; set; }
}
I am stuck as to how to represent this in Fluent NHIbernate. In the database, I don't need both a Replaces and ReplacedBy field - I can get the info from just one of them. But I think I need both in my object for NHibernate to figure it out.
Currently, I have this, but it generates no database mappings at all:
mapping.HasOne(t => t.ReplacedBy).ForeignKey("Id").Class(typeof(Item));
As always, any thoughts greatly appreciated!
A HasOne or one-to-one relationship is a bit of a special relationship in NHibernate. It's (typically) an inferred relationship between two separate tables, whereby records that share a primary key value are associated. It's unlikely you'd be able to get a HasOne working for your situation. I have a post on my blog, I think you mean a many-to-one, sir, which goes into some of the misconceptions of HasOne relationships.
Instead you should look at using References, which is a many-to-one relationship, and does support self referential relationships.

How to find if a referenced object can be deleted?

I have an object called "Customer" which will be used in the other tables as foreign keys.
The problem is that I want to know if a "Customer" can be deleted (ie, it is not being referenced in any other tables).
Is this possible with Nhibernate?
What you are asking is to find the existence of the Customer PK value in the referenced tables FK column.
There are many ways you can go about this:
as kgiannakakis noted, try to do the delete and if an exception is thrown rollback. Effective but ugly and not useful. This also requires that you have set a CASCADE="RESTRICT" in your database. This solution has the drawback that you have to try to delete the object to find out that you can't
Map the entities that reference Customer as collections and then for each collection if their Count > 0 then do not allow the delete. This is good because this is safe against schema changes as long as the mapping is complete. It is also a bad solution because additional selects will have to be made.
Have a method that performs a query like bool IsReferenced(Customer cust). Good because you can have a single query which you will use when you want. Not so good because it may be susceptible to errors due to schema and/or domain changes (depending on the type of query you will do: sql/hql/criteria).
A computed property on the class it self with a mapping element like <property name="IsReferenced" type="long" formula="sql-query that sums the Customer id usage in the referenced tables" />. Good because its a fast solution (at least as fast as your DB is), no additional queries. Not so good because it is susceptible to schema changes so when you change your DB you mustn't forget to update this query.
crazy solution: create a schema bound view that makes the calculation. Make the query on it when you want. Good because its schema-bound and is less susceptible to schema changes, good because the query is quick, not-so-good because you still have to do an additional query (or you map this view's result on solution 4.)
2,3,4 are also good because you can also project this behavior to your UI (don't allow the delete)
Personally i would go for 4,3,5 with that preference
I want to know if a "Customer" can be deleted (ie, it is not being referenced in any other tables).
It is not really the database responsibility to determine if the Customer can be deleted. It is rather part of your business logic.
You are asking to check the referential integrity on the database.
It is ok in non OOP world.
But when dealing with objects (like you do) you better add the logic to your objects (objects have state and behavior; DB - only the state).
So, I would add a method to the Customer class to determine if it can be deleted or not. This way you can properly (unit) test the functionality.
For example, let's say we have a rule Customer can only be deleted if he has no orders and has not participated in forum.
Then you will have Customer object similar to this (simplest possible case):
public class Customer
{
public virtual ISet<Order> Orders { get; protected set; }
public virtual ISet<ForumPost> ForumPosts { get; protected set; }
public virtual bool CanBedeleted
{
get
{
return Orders.Count == 0 && ForumPosts.Count == 0
}
}
}
This is very clean and simple design that is easy to use, test and does not heavily relies on NHibernate or underlying database.
You can use it like this:
if (myCustomer.CanBeDeleted)
session.Delete(mycustomer)
In addition to that you can fine-tune NHibernate to delete related orders and other associations if required.
The note: of course the example above is just simplest possible illustrative solution. You might want to make such a rule part of the validation that should be enforced when deleting the object.
Thinking in entities and relations instead of tables and foreign keys, there are these different situations:
Customer has a one-to-many relation which builds a part of the customer, for instance his phone numbers. They should also be deleted by means of cascading.
Customer has a one-to-many or many-to-many relation which is not part of the customer, but they are known/reachable by the customer.
Some other entity has a relation to the Customer. It could also be an any-type (which is not a foreign key in the database). For instance orders of the customer. The orders are not known by the customer. This is the hardest case.
As far as I know, there is no direct solution from NHibernate. There is the meta-data API, which allows you to explore the mapping definitions at runtime. IMHO, this is the wrong way to do it.
In my opinion, it is the responsibility of the business logic to validate if an entity can be deleted or not. (Even if there are foreign keys and constraints which ensures integrity of the database, it is still business logic).
We implemented a service which is called before deletion of an entity. Other parts of the software register for certain types. They can veto against the deletion (eg. by throwing an exception).
For instance, the order system registers for deletion of customers. If a customer should be deleted, the order system searches for orders by this customer and throws if it found one.
It's not possible directly. Presumably your domain model includes Customer's related objects, such as Addresses, Orders, etc. You should use the specification pattern for this.
public class CustomerCanBeDeleted
{
public bool IsSatisfiedBy(Customer customer)
{
// Check that related objects are null and related collections are empty
// Plus any business logic that determines if a Customer can be deleted
}
}
Edited to add:
Perhaps the most straightforward method would be to create a stored procedure that performs this check and call it before deleting. You can access an IDbCommand from NHibernate (ISession.Connection.CreateCommand()) so that the call is database agnostic.
See also the responses to this question.
It might be worth looking at the cascade property, in particular all-delete-orphan in your hbm.xml files and this may take care of it for you.
See here, 16.3 - Cascading Lifecycle
A naive solution will be to use a transaction. Start a transaction and delete the object. An exception will inform you that the object can't be deleted. In any case, do a roll-back.
Map the entities that reference Customer as collections. Name each collection in your Customer class with a particular suffix.For example if your Customer entity has some Orders, name the Orders collection as below:
public virtual ISet<Order> Orders_NHBSet { get; set; } // add "_NHBSet" at the end
Now by using Reflection you can get all properties of Customer at run time and get those properties that their names ends with your defined suffix( In this case "_NHBSet" ) Then check each collection if they contain any element and if so avoid deleting customer.
public static void DeleteCustomer(Customer customer)
{
using (var session = sessions.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
var listOfProperties =typeof(Customer).GetProperties();
foreach (var classProperty in listOfProperties )
{
if (classProperty.Name.EndsWith("_NHBSet"))
{
PropertyInfo myPropInfo = typeof(Customer).GetProperty(classProperty.Name);
dynamic Collection = myPropInfo.GetValue(customer, null);
if (Enumerable.FirstOrDefault(Collection) !=null)// Check if collection contains any element
{
MessageBox.Show("Customer Cannot be deleted");
return;
}
}
}
session.Delete(customer);
transaction.Commit();
}
}
}
The Advantage of this approach is that you don't have to change your code later if you add new collections to your customer class.And you don't need change your sql query as Jaguar suggested.
The only thing you must care about is to add the particular suffix to your newly added collections.

What is the best way to use nested Objects with Subsonic when I only have Iqueryable for Foreign Key Relationships

I'd like to use Subsonic in a shopping cart application, but I'm trying to replace code that is using Session to store an Order object. That Order object has a collection or OrderDetail objects that are added to the collection through the shopping cart process. I'm impressed with what Subsonic can do and I think I'm missing how I could implement it in this project. What I need is:
Order.OrderDetails.Add(new OrderDetail());
Right now Subsonic is creating the one-to-many relationship for me based on the foreign key in the OrderDetails table. But Order.OrderDetails is available as an Iqueryable interface. I would like more control over how the property is managed. How have other managed to use the Subsonic generated objects to hold data in memory before saving to the database?
You could add another property via a partial class and use that instead of the generated one:
public partial class Order {
public IList<OrderDetail> Details { get; set; }
}

NHibernate/ActiveRecord - Any way to map to a foreign key column only?

I'm using Castle ActiveRecord, but this question applies to NHibernate, too, since a solution that works with NHibernate should work for ActiveRecord. Anyway, what I have is an underlying table structure like this:
TableA -hasMany-> TableB
I have corresponding objects EntityA and EntityB. EntityA has an IList of EntityB objects. This part works fine. Now, I want EntityB to have some kind of reference back to EntityA. I know I can use the BelongsTo attribute on EntityB to give it an actual reference back to the full EntityA type, like:
[BelongsTo("tableAid")]
public EntityA Parent { get; set; }
But what I'd really like to do is:
[BelongsTo("tableAid")]
public int ParentId { get; set; }
So, EntityB would store only the ID of the parent object, not a reference to the actual object. This is a trivial example, but I have good reasons for wanting to go with this approach. In the application I'm working on, we have pages that display specific EntityB-like objects, and we'd like for those pages to include links (as in hyperlinks) to the corresponding parent pages. We can do that by using the first approach above, but that requires that the entire EntityA object be loaded when all I really need is the ID. It's not a huge deal, but it just seems wasteful. I know I can use lazy-loading, but again, that seems more like a hack to me...
I have tried flagging the foreign key with the [Property] attribute like so:
[Property]
public int ParentId { get; set; }
The problem with this approach is that EntityB.ParentId remains null when you do a EntityA.SaveAndFlush() on a new object tree. The correct value is being written to the database, and I can force the value back into EntityB.ParentId by doing an EntityA.Refresh(), but again, that seems like a bit of a hack.
Lazy loading is exactly what you want - and it's not a hack either, it's a well tested and baked in part of NHIbernate and an important tool when performance tuning any substantial NHibernate app.
If you were to mark your "parent" EntityA as lazy loaded, referring to EntityB.Parent.Id would not load EntityA at all (as behind the scenes NHIbernate has already loaded EntityA's id when loading EntityB) - thus letting you setup your links without incurring a performance penalty.
Just this:
[Property] public int ParentId { get; set; }
...assuming ParentId is the actual column name.
A couple of other comments.
First, you should consider lazy loading many-to-one properties anyway. If you eagerly load them, you must be aware of possible cascades of eager loads, which can make a serious performance hit. To do this you must mark all public members of the lazily loaded class as virtual.
Second, be aware that any time you have a one-to-many association with no corresponding relation from the child back to the parent, you must make the FK nullable in the database. That's because when NH creates new child items, it will insert it with the parent id null and then in a second step update it.