在LINQ to SQL中,我如何做到这一点,以便可以在不先保存实体的情况下将项目添加到实体的集合中?
时间:2020-03-05 18:50:19 来源:igfitidea点击:
var e1 = new E1(); e1.e2s.Add(new e2()); //e2s is null until e1 is saved, i want to save them all at the same time context.e1s.imsertonsubmit(e1); context.submitchanges();
解决方案
回答
好吧,我不知道初始代码块是否可以工作,但是我猜我们必须将新的e2标记为提交时插入。因此:
var e1 = new E1(); var e2 = new e2(); e1.e2s.Add(e2); //e2s is null until e1 is saved, i want to save them all at the same time context.e1s.insertonsubmit(e1); context.e2s.insertonsubmit(e2); context.submitchanges();
回答
我们走了,显然当我们创建另一个ctor时,我们实际上必须调用no arg ctor才能使ctor中的内容发生
回答
如果我们为DataClasses在这些类之间建立关联,则子项将与主项一起保存,甚至标识也将正确设置。
我们可以通过如下方式将LoadOptions添加到O / R-Designer数据类中来实现:
MyDataContext mydc = new MyDataContext(); System.Data.Linq.DataLoadOptions lo = new System.Data.Linq.DataLoadOptions(); lo.LoadWith<E1>(p => p.e2s); mydc.LoadOptions = lo;
这样,LINQ将负责添加子项,我们不需要自己单独插入每个子项。
副作用:加载项目时,子项目也会被检索。