Linq to SQL EntitySet Records causing duplicate insertion
In a WPF application i'm using Linq to SQL in a multi tier application.
(This is an archailogy photo filing application), so every excavatio开发者_开发技巧n has its corresponding Pictures, thus a one-to-many relationship. This relationship is correctly created by SQLMetal (which i'm using to create the POCOs).
So here is the situation i 'm having trouble with:
Saving changes (either of new or altered objects) is done through UnitOfWork() pattern this way:
using (IUnitOfWork unitOfWork = UnitOfWork.Begin())
{
//if this is a new record
if (SelectedExcavation.excavation.ExcavationId == 0)
{
IsNewRecord = true;
excavService.Add(SelectedExcavation.excavation);
}
//send the actual changes to the dbms
unitOfWork.Commit();
}
Everything works fine!
BUTTTT!!!
Whenever a record gets updated which has (already at least one ) corresponding Picture Record:
1) a new Excavation Record is inserted
2) the current Excavation Record gets updated
3) the previous Picture Record gets its Id changed to the newly created ExcavationId
What is going on under the hood? Does Linq to SQL not handle such simple update scenarios?
Thanks in advance
In this WPF application i'm using Unity to register the IDataContext which is passed as a constructor parameter to the IUnitOfWork.
I'm actually using multi-tier architecture (which should always give me a separate IUnitOfWork object and hence a separate IDataContext), but i want to fake this behavior to make IUnitOfWork to be always the same Instance (and hence the IDataContext instance to be the same everywhere in my application).
This means that the application is using actually a (classical) two tier application in regards of the datacontext!
... and the instances i get resolved (using Unity) are actually the same everywhere in my application (i used the GetHashCode() of those, to confirm this).
So everything seems to work as expected!
But as i stated in my previous post, whenever a record has corresponding EntitySet records and gets updated the Datacontext does immediately (in this sequence):
1) an insert of the master record with the values that were originally in the record prior to change
2) an update of detail record changing its Id to the new master record in step 1)
3) an update of the master record with the changed (new) values.
Steps 1) and 2) should NEVER appear, whereas only step 3) is the correct one (and should be the only one appearing in the Datacontext.
I read in a lot of blogs that you have to Attach/Detach and do some black magic things to overcome this situation, but as i sad: there is only one and the same DataContext everywhere, so the records are always attached to it, so this phenomenon should not appear! (or am i missing something)!???
Any help is appreciated!
精彩评论