對於難以理解的標題,我很抱歉!EF 4.0:添加新數據的最佳方式
我想要的很簡單,我有這些表:
Maintable(ID)
Child1(MainTableID, ID)
Child2(MainTableID, ID)
Child3(MainTableID, ID)
Child4(MainTableID, ID)
CHILD2,Child3和Child4從Child1創建的,所以我重新創建每次Maintable或Child1改變:
Child2 = GetChild2FromChild1()
Child3 = GetChild3FromChild1()
Child4 = GetChild4FromChild1()
在那之後,我只是簡單的刪除舊錶,並保存新創建:
using (var context = new EF())
{
context.DeleteObject(child2); // only the ones belong to Maintable
context.DeleteObject(child3);
context.DeleteObject(child4);
}
using (var context = new EF())
{
// because i always delete child2->4 , so i always set their state to be Added
// here i will add the new tables, something like this :
foreach (var child2 in Maintable.child2)
{
counterID--;
child2.State = State.Added;
child2.ID = counterID;
}
context.SaveChanges();
}
我知道這很難理解,所以這裏的步驟:
- 實體
Maintable
包含四個子表(1-> 4) - 每次我需要更新實體
Maintable
,我將不得不刪除: Maintable.Child2,Maintable.Child3,Maintable.Child4,除了Child1 - 那麼我會追加新的數據CHILD2,Child3,Child4
但這種方法真是一個痛苦的屁股,我不斷收到錯誤,我很難弄清楚爲什麼,和奇怪的結果等等,比如我在發佈這個問題之前等了一個下午的調試,沒有任何積極的進展!
所以我要問的是什麼有另一種方式這將滿足我的需求,但也是一個「乾淨」的一個,因爲我覺得我的問題是不是很複雜,我不是很熟悉C#
這可能是我,但我沒從你問明白一件事。對其他人也可能是這樣,考慮修改你的問題。 – Peter 2014-09-11 09:52:30
你想添加新行嗎?或更新行?你的問題實際上並不那麼清楚:/ – 2014-09-11 09:58:43
等待我編輯它,當你使用'using(var context = new EF())'時,在這裏感謝 – NeedAnswers 2014-09-11 09:59:23