Question

I'd like to know if the next problem can be solved in a different way in NHibernate.

Let's say we've this domain:

public class A 
{
     public virtual B LastAssociationWithB { get; set; }
     public virtual ICollection<B> CollectionAssociationOfB { get; set; }
}

public class B
{
     public virtual DateTime DateAdded { get; set; }
}

The LastAssociationWithB property represents one of the B persistent objects associated in the CollectionAssociationOfB collection property.

Actually, LastAssociationWithB represents the last B persistent object added by date.

So, in the domain, when a new B is added to CollectionAssociationOfB, it's also assigned to LastAssociationWithB.

This is a good way of later turning code into less complex LINQ queries.

Anyway, my question is: do you know any other approach to this? For example, some kind of many-to-one association that produces a SQL join under the hoods so you wouldn't need to have an explicit 1:n relation in the A table but it would maintain the class property?

Or is my current approach the recommended way of solving this scenario?

Side note: in the real-world scenario that CollectionAssociationOfB is an ordered list as ordering is specified in the NHibernate mapping configuration.

Was it helpful?

Solution

You could specify the relationship using a formula:

whether this is better or not is debatable.. it depends on your circumstances - one the one hand it ensures consistency, but on the other hand it will probably have a performance penalty when querying - so it really depends on your own specific case.

Another alternative is to use a trigger on insert into B to update the column in A. This has the downside of moving logic into the database, but it would ensure consistency without the potential performance penalty.

You could also achieve the equivalent of a trigger by using an NHibernate event to intercept saving B and then updating A - with the benefit of the logic remaining in your code, but the downside that any direct updates to the database could introduce inconsistency.

Of course both trigger options obfuscate the logic somewhat, as opposed to having a method on A or B that does the logic. I would personally probably put a method in A to add a new B and update the association, but then you would need to ensure that no-one updates the B collection directly and bypasses your method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top