views:

88

answers:

1

I have a pretty complex object graph G with an object o1 in G. G is to be written into a database using NHibernate. However, if there already is a persistent entry of o1 (let's call it o1_p ) in the database, I substitute o1 for o1_p. Hence there should be no redundant entries in the database. Now I let NHibernate do its job and afterwards I look into the database. Now I have exactly the situation I tried to avoid. There are entries for the original o1_p object plus o1 in the database. The only explanation I have so far is that o1 is reachable via another route in G so hibernate puts it into the database. Is there a way I can determine if this is the case, i.e. can I ask the garbage collector how many references there are to o1. Or to speak in graph language: How many incoming edges does o1 have?

+1  A: 

No, you can't ask the garbage collector how many references there are to o1: .NET doesn't use reference counting.

Basically you'd have to do all the graph navigation yourself, which will probably mean making your object graph implement some sort of visitor algorithm, combined with a cache of objects you've already examined. And yes, this is similar to what the GC would do, but I don't believe there's any way of hooking into its processing. (And there are probably edge cases involving special tricks where the GC knows something isn't garbage and ignores it anyway, which wouldn't be suitable for your code.)

Jon Skeet