编辑更好地隔离错误;见下文。
我在C#Code-First EF模型中有一个ParentObject
和ChildObject
类:
public class ParentObject{
[Key]
public int Key{get; set;}
[Required]
public string Name {get; set;} //unique identifier
public HashSet<ChildObject> TheChildren {get; set;}
}
public class ChildObject{
[Key]
public int Key {get; set;}
public int ParentKey {get; set;}
public string Name {get; set;}
[NotMapped]
string ParentName {get; set;}
}
public class FamilyDB : DbContext{
public DbSet<ParentObject> Parents { get; set; }
public DbSet<ChildObject> Children { get; set; }
public FamilyDB(): base(){
this.Parents.Load(); this.Children.Load();
}
}
我想从一组CSV文件中填充FamilyDB
数据库。 Parents
已经存在;我只需要为每个TheChildren
覆盖并分配ParentObject
。
但我总是以错误结束:
public static void ImportChildFile(FamilyDB connxn, string csvPath){
List<ChildObject> records = GetChildrenFromCsvFile(csvPath);
var groupedRecords = records.GroupBy(x => x.ParentName);
foreach (var recordSet in groupedRecords){
parentName = recordSet.Key;
ParentObject matchingParent = connxn.Parents.
Where(x => x.Name = parentName).FirstOrDefault();
if (matchingParent == null)
throw new ArgumentException("No prnt named " + parentName);
//Want to overwrite, not add - must remove all current children
while (matchingParent.Children.Count > 0)
connxn.TheChildren.Remove(matchingParent.Children.Last());
matchingParent.TheChildren.UnionWith(recordSet);
//connxn.SaveChanges(); //this would work if it was here
}
connxn.SaveChanges();
/*Multiplicity constraint violated.
The role 'ParentObject_Children_Source' of
the relationship 'MyNamespace.ParentObject_Children'
has multiplicity 1 or 0..1.*/
}
该错误消息似乎指责我分配给相同的ParentObject
两次,但我没有这样做,因为每个recordSet
对应不同的ParentName
(因此也就是父母。那么是怎么回事?