c# - Which algorithm to use with many-to-many relation in NHibernate -


I have many-to-many relationships between photos and tags: a photo can have multiple tags and many photos Can I share the same tag

I have a loop that scans photos in a directory and then adds them to NHibernate. Some tags are added to photos during that process, eg. A 2009-tag when taken in photo 200 9.

An equally and gatehashcode is applied in the tag category and uses the name property as a signature property only. Both photos and tags are the key to rent and versions.

I have some code like the following:

  Public Zero Import () {... foreach (var fileName fileNames) {var photo = new photo {FileName = FileName}; AddDefaultTags (_session, photo, fileName); _session.Save (photo); } ...} Add Private Zero AddDefaultTags (...) {... var tag = _session.CreateCriteria (typeof (tag)). (Restriction "." ("Name", year.ToString ()). Unicrus result & lt; Tag & gt; (); If (tag! = Null) {photo.AddTag (tag); } Else {var tag = new tag {name = year.ToString ())}; _session.Save (tag); Photo.AddTag (tag); }}  

My problem occurs when the tag does not exist, e.g. The first picture of a new year. The addDefaultTags method checks that the tag exists in the database and then creates it and connects to NHibernate. It works very well in adding a picture, but when importing many photos in the new year and the same unit of work Within, this fails because it is still not present in the database and it has been added again. This fails when completing the work unit because it tries to add two entries in the tag table with the same name ...

My question is, there are ways to ensure that NHibernate tries to create only one tag Databases in the above situation Do I need to retain the list of newly added tags or can I set the mapping in such a way that it works?

You need to run _session.Flush () if your criteria Should not return the forced data or you should be able to do this correctly by setting _session.FlushMode

with FlushMode.Auto, before the criteria are executed The session will be automatically shot.

EDIT: And important! When you read the code shown, it does not appear that you are using the transaction for the unit of your work. I advise to wrap my unit of work in the transaction - if you have NH 2.0 +! If you are using Flushmode to work, Auto is required!

Read more here:


Comments

Popular posts from this blog

python - Overriding the save method in Django ModelForm -

html - CSS autoheight, but fit content to height of div -

qt - How to prevent QAudioInput from automatically boosting the master volume to 100%? -