saveChanges problem

本文关键字:problem saveChanges | 更新日期: 2023-09-27 18:06:19

我试图从数据库中删除项目,但我得到以下例外:

"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();

saveChanges problem

当你调用这个时:

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