我花那麼多時間試圖實現一個通用的方法來添加或更新與相關實體(關係一對多)一個實體,但我堅持......實體框架6:泛型方法AddOrUpdate
方法必須接收2個參數,第一個是父母,第二個是孩子。我們的目標是子實體保存到父(添加如果它不存在或更新)
有泛型方法簽名:
public static bool AddOrUpdate<T,U>(T ItemToSave,U ItemRelated, int ID) where T : class where U : class
{
using (var context = new dbContext())
{
var parent = context.Set<T>().Find(ID);
if (parent == null) return;
// how to retrieve now the child (ItemRelated) from the parent (ItemToSave) in order to add into it or update ?
return context.SaveChanges() > 0;
}
}
這種方法位於一個靜態類「服務」 和我希望能夠從任何類中調用Service.AddOrUpdate(Order _order,OrderLine _orderline,_order.OrderId)。
我被困在檢索從父母的孩子,並添加或更新到它。
任何人都可以請幫助我實現這一目標嗎?
那麼你到底在嘗試什麼? 「??」顯然不會工作 –
對不起,我完成了我的問題 –
不,他們是2實體集,ItemToSave可以有0個或更多ItemRelated –