循环导入文件时违反了EF Code-first多重性约束

时间:2012-07-25 19:00:01

标签: c# entity-framework code-first multiplicity

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

我在C#Code-First EF模​​型中有一个ParentObjectChildObject类:

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(因此也就是父母。那么是怎么回事?

0 个答案:

没有答案