saveChanges问题

时间:2011-08-21 07:14:24

标签: c# database entity-framework-4.1

我正在尝试从数据库中删除该项目,但我得到以下异常:

"DbUpdateException was unhandled"

------------------------------------------------------------
public class Project
{
    public Project()
    {
        Customers = new List<Customer>();
        Materials = new List<Material>();
        Workers = new List<Worker>();
    }

    [Key]
    public long ProjectID { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime DateFinished { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }

    //Customer TheCustomer = new Customer();

    public ICollection<Customer> Customers { get; set; }
    public ICollection<Material> Materials { get; set; }
    public ICollection<Worker> Workers { get; set; }
}

------------------------------------------------------------------------
if (cb_Projects.SelectedValue != null)
{
    using (var db = new ProjectContext())
    {

        Project p = db.Projects.Find(cb_Projects.SelectedValue);
        if (db.Entry(p).State == EntityState.Detached)
        {
            db.Projects.Attach(p);
        }

        p.Customers.Clear();
        p.Workers.Clear();
        p.Materials.Clear();
        db.Projects.Remove(p);
        db.SaveChanges();

1 个答案:

答案 0 :(得分:3)

当你这样称呼时:

p.Customers.Clear();
p.Workers.Clear();
p.Materials.Clear();

您注意到,因为只有在这些关系是一对多的情况下填充集合时,它才有效,您还需要在每个单独的依赖实体上进行减法(调用Remove)。要填充这些集合,您必须使用预先加载

long selectedValue = cb_Projects.SelectedValue;
Project p = db.Projects.Include(p => p.Customers)
                       .Include(p => p.Workers)
                       .Include(p => p.Materials)
                       .Single(p => p.ProjectID == selectedValue);

或将所有三个属性标记为virtual以启用延迟加载。

您当前的代码应由级联删除处理。

这也没有多大意义:

if (db.Entry(p).State == EntityState.Detached)
{
    db.Projects.Attach(p);
}

您正在上下文的新实例中搜索项目,因此它将始终从数据库加载,其状态为Unchanged