开发者

Linq2SQL: DeleteAllOnSubmit discriminates entities being re-added?

Encountering some weird behaviour with Linq:

Situation:

  1. I have a many to many relationship between two entities: UserProfile and BusinessUnit (joined in UserProfile_BusinessUnit table).

  2. Using a ListBox, a user can multi-select BusinessUnits a UserProfile belongs to.

  3. When UPDATING the record, I call:

    dataContext.UserProfile_BusinessUnit.DeleteAllOnSubmit(userProfile.BusinessUnits); dataContext.SubmitChanges();

  4. This ends up deleting the records from UserProfile_BusinessUnit

  5. I then add the entries back in from the multi-select using a foreach

    foreach (var b in model.BusinessUnitsSelected) { userProfile.BusinessUnits.Add(GetBusinessUnitAsEntity(b.ToString())); } dataContext.SubmitChanges();

The Issue:

Only NET NEW BusinessUnits are added back to the relationship. If a BusinessUnit remains selected and is addressed as part of the DeleteAllOnSubmit, it does not get re-added... it's like the dataContext continues to see the record as marked for deletion (even though I开发者_JAVA百科've already called SubmitChanges())...

EDIT: I tried removing the SubmitChanges() between calls to see if it would resolve but it only ends up deleting all entries and does not re-add...

EDIT: I added the following to make it work... seems like a hack to me:

 dataContext = null;
 dataContext = new UserProfileDataContext();

Shouldn't there be a way to cause the datacontext to "commit" and move on?

Any ideas on how I can proceed? I thought about dumping the DeleteAllOnSubmit, and explicitly comparing what is going in vs. out... but this seems like a lot more work than I should need to do...

Thanks!

The Code:

dataContext.UserProfile_BusinessUnits.DeleteAllOnSubmit(userProfile.UserProfile_BusinessUnits);
dataContext.SubmitChanges(); // all records deleted

foreach (var b in model.BusinessUnitsSelected)
   {
     userProfile.BusinessUnits.Add(GetBusinessUnitAsEntity(b.ToString()));
   }
cx.SubmitChanges(); // only net new being added


Try this:

foreach (var b in model.BusinessUnitsSelected) 
   { 
     var unit = GetBusinessUnitAsEntity(b.ToString());
     userProfile.BusinessUnits.Add(unit); 
     db.BusinessUnits.InsertOnSubmit(unit);
   } 

Where you add to the local collectionand to the main business units table too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜