开发者

Deleting entities in EF4...different scenarios how to handle

I have a Answer table which has pk_answerid, answertext , fk_questionid, chosenoptions stored as 1,3,2 (comma separated)

answertext if populated, then chosenoptions null and if chosenoptions if populated then answertext is null.

ChosenOption table has struct开发者_如何学JAVAure pk_chosenoptionid, fk_questionid In EntityFramework 4, I have something along these lines

void SaveAnswers(ICollection<Answer> answers)
{
        context.Answers.Add(answers);
        context.SaveChanges();
}

This works fine....but when in the UI I go back to page which is wizard with Q&A's on different pages and I deselect all answers previously selected, and click save, no answers are deleted. I also tried DeleteObject which does not delete the Answers and chosenoptions even though I have cascade delete on the Answer table to Chosen option table. Also in edit scenarios if for e.g. if the User selected option 1,2 and then saves it and then goes back and selects 3,2 how do you write code in EF to do such complex stuff. I haven't come across any tutorials which explain such scenarios. Most of what I have seen is simple add, delete and applypropertychanges. I have an MVC app, which has lazy loading enabled. Pls help and suggest some sort of code using an example or any pointers to existing blogs where this is explained.


EF doesn't take care - I shame to posting this again and again but I really don't like to explain it every time: Update relationships when saving changes of EF4 POCO objects

Check that explanation. Your problem is similar. You persisted entity graph (set of related entities) and now you want to change the graph. Your new graph is extracted from web request which mean it is detached and EF doesn't know what has changed. You must do it manually - I just discussed what does it mean to do it manually in another question = it is usually too complex.

The easiest way is your current approach - delete everything and add it again but it is really ugly. Another approach is loading the graph from database and manually merge all changes you get from the request = compare these two graph and update the loaded (attached). Be aware that you must manually call DeleteObject for anything you want to delete from the database. Then just call SaveChanges.

Btw. if you are doing wizard why don't you just store current state in session and save everything once user completes the wizard? You will avoid all these complications.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜