开发者

saveChanges problem

开发者 https://www.devze.com 2023-03-29 19:57 出处:网络
I am trying to delete the project from the database but I get the following exception: \"DbUpdateException was unhandled\"

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.Pro开发者_开发知识库jects.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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号