【发布时间】: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