2

编辑更好地隔离错误;见下文。

我在 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();
    }
}

我想FamilyDB从一组 CSV 文件中填充一个数据库。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(因此是父母)。那么发生了什么?

4

0 回答 0