【问题标题】:Add detached object and skip depending objects in EF CodeFirst在 EF Code First 中添加分离对象并跳过依赖对象
【发布时间】:2013-12-02 12:23:40
【问题描述】:

目标是将分离的根对象添加到数据库并跳过添加依赖的子对象。我试图调用 dbSetRoot.Add(root) 方法将根对象附加到上下文。并将 Child 对象的状态设置为 Unchanged 以在 SaveChange 上跳过此对象。

public class Root
{
    [System.ComponentModel.DataAnnotations.Key]
    public int ID { get; set; }
    public string Name { get; set; }
    public IList<Child> Childs { get; set; }
}
public class Child
{
    [System.ComponentModel.DataAnnotations.Key]
    public int ID { get; set; }
    public int RootID { get; set; }
    public string Name { get; set; }
}

代码

 // Prepare data to save
        Root root = new Root()
        {
            Name = DateTime.Now.ToLongTimeString()
        };
        root.Childs = new List<Child>();
        root.Childs.Add(new Child()
        {
            Name = DateTime.Now.ToLongTimeString()
        });

        // Save to DB
        using (TasksDbContext dbContext = new TasksDbContext())
        {
            DbSet dbSetRoot = dbContext.Set<Root>();                
            dbSetRoot.Add(root);
            dbContext.Entry(root.Childs[0]).State = System.Data.EntityState.Unchanged;
            dbContext.SaveChanges(); // exception is here
        }

此代码抛出异常“发生引用完整性约束冲突:定义引用约束的属性值在关系中的主体对象和依赖对象之间不一致。”在 SaveChanges() 方法上。

【问题讨论】:

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


    【解决方案1】:

    您已经使用 new 运算符创建了 Child,它的 ID 将为“0”。

    然后您将它添加到Root,并告诉上下文它是未更改的。

    因此,现在您尝试保存链接到 ID 为 0 的 ChildRoot 对象,但该子对象在数据库中不存在,因此您违反了参照完整性约束。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      相关资源
      最近更新 更多