EDIT Better isolated the error; see below.
I have a ParentObject
and ChildObject
class in a C# Code-First EF model:
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();
}
}
I'd like to populate a FamilyDB
database from a set of CSV files. The Parents
already exist; I just need to overwrite and assign TheChildren
for each ParentObject
.
But I always end up with an error:
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.*/
}
That error message seems to accuse me of assigning to the same ParentObject
twice, but I did no such thing, as each recordSet
corresponds to a different ParentName
(and thus parent.) So what is going on?