我正在尝试在两个具有FK关系(一对多)的表上使用EF(模型优先)批量插入。下面的代码正确插入了所有Challenge条目,但只插入了一次X次短缺。我的期望......我有10个短缺,有2个挑战。我应该收到2个挑战条目和20个短缺条目。我只看到插入第一次短缺的10个挑战条目。 (以下代码简化)
//class for cloning Shortage collection
public class ShortageCollection : Collection<Shortage>
{
public ShortageCollection(IList<Shortage> source) : base(source) { }
public ShortageCollection() { }
public ShortageCollection Clone()
{
return Clone(this);
}
public static ShortageCollection Clone(ShortageCollection shortage)
{
var res = new ShortageCollection();
foreach (var s in shortage)
{
res.Add(s.Clone());
}
}
}
public class Shortage : StandardDB.Shortage
{
public Shortage Clone()
{
return new Shortage()
{
PART_NUMBER = this.PART_NUMBER,
Note = this.Note,
Qty = this.Qty,
ResponseMachine = this.ResponseMachine
};
}
}
public void CreateChallenge()
{
var JSONJobs = new JavaScriptSerializer().Deserialize<string[]>(Jobs);
var JSONParts = new JavaScriptSerializer().Deserialize<ChallengePartsList[]>(Parts);
using (ARTEntities art = new ARTEntities())
{
art.Configuration.AutoDetectChangesEnabled = false;
art.Configuration.ValidateOnSaveEnabled = false;
ShortageCollection sColl = new ShortageCollection();
foreach(var part in JSONParts)
{
Shortage s = new Shortage()
{
PART_NUMBER = part.Invid,
Note = Challenge,
Qty = part.Qty,
ResponseMachine = ResponseMachine
};
sColl.Add(s);
}
foreach (var job in JSONJobs) {
Challenge c = new Challenge()
{
InitiatorORG = Org,
TypeID = TypeID,
DISCRETE_JOB = job,
InitiatorPERSON_ID = InitiatorPersonID,
InitiatedDate = datenow,
Challenge1 = Challenge,
ChampionGroupID = ChampionGroupID,
StatusID = StatusID,
InitiatorGroupID = InitiatorGroupID,
DivisionID = DivisionID,
Shortages = sColl.Clone()
};
art.Challenges.Add(c);
}
art.SaveChanges();
}
}
答案 0 :(得分:2)
你只在内存中创造10个短缺。您的Clone
方法是浅层克隆,不会通过并克隆每个对象。因此,您有2个列表,其中包含10个相同的项目(每对项目指向完全相同的内存引用)。
您需要做的是DeepClone,如下所示:
public static ShortageCollection Clone(ShortageCollection shortage)
{
var res = new ShortageCollection();
foreach(var s in shortage) {
res.Add( s.Clone() );
}
return res;
}
在您的短缺课程中:
public class Shortage
{
public Shortage Clone()
{
return new Shortage()
{
SomeProp = this.SomeProp,
SomeOtherProp = this.SomeOtherProp
}
}
}
请注意,如果内部短缺中的任何一个对象指向另一个实体,则每对都将指向同一个实体。
搜索DeepClone以获取更多信息