Adding or removing child entities in TransferFormValuesTo()

24 views
Skip to first unread message

Ingo

unread,
Dec 7, 2012, 12:14:06 PM12/7/12
to sharp...@googlegroups.com
Hi,

I'm tearing my hair over a basic functionality which I can't get to work.

I which to add or remove a child entity in the TransferFormValuesTo() function. My code is pretty simple:

        protected override void TransferFormValuesTo(Product toUpdate, Product fromForm)
        {
            toUpdate.Category = fromForm.Category;

            foreach (var file in fromForm.Files)
            {
                toUpdate.AddFile(file);
            }
        }

If I create the entity from scratch it works just fine, but if I edit an existing entity then NHibernate throws this exception:
NonUniqueObjectException
a different object with the same identifier value was already associated with the session: 7, of entity: MyProject.Domain.Entities.Product

Does anybody know what the cause of the exception can be. I know that it means that NHibernate somehow thinks I have to objects of the Product entity in memory somewhere but if I just skip the call to "toUpdate.AddFile(file)", everything is fine and all other properties are saved. BTW, here is the code for AddFile():

        public virtual void AddFile(ProductFile file)
        {
            if (file != null && !files.Contains(file))
            {
                files.Add(file);
            }
        }

Thanks in advance!
/Ingo

Billy McCafferty

unread,
Dec 14, 2012, 5:38:18 PM12/14/12
to sharp...@googlegroups.com
Hi Ingo,

Certainly sounds fishy.  What does ProductFile look like?  Also, are you able to successfully do the reverse wherein you create/save ProductFiles instead of adding them to Product; e.g., 

        protected override void TransferFormValuesTo(Product toUpdate, Product fromForm)
        {
            toUpdate.Category = fromForm.Category;

            foreach (var file in fromForm.Files)
            {
                file.Product = toUpdate;
            }
        }

Not sure if that jives with your code but you get the idea.

Billy McCafferty
Reply all
Reply to author
Forward
0 new messages