问题描述:

I am trying to delete the project from the database but I get the following exception:

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

网友答案:

When you called this:

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

You did noting because it only works if collections are populated moreover if those relations are one-to-many you will also need to delate (call Remove) on every single dependent entity. To populate those collections you must either use eager loading

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

or mark all three properties as virtual to enable lazy loading.

Your current code should be handled by cascade delete.

This also doesn't make much sense:

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

You are searching for the project in the new instance of the context so it will always be loaded from the database and its state will be Unchanged.

相关阅读:
Top