0

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(); 
4
  • 2
    post the inner exception message of DbUpdateException Commented Aug 21, 2011 at 7:22
  • The code you posted appears to be incomplete. Commented Aug 21, 2011 at 7:22
  • i guess you have some smaller/bigger-characters in there - use &gt or &lt instead of those characters Commented Aug 21, 2011 at 7:25
  • When you clear your Customers "p.Customers.Clear();" you are changing the entity state to Updated, you mustn't change the state to Updated. Commented Aug 21, 2011 at 7:37

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.