1

I want to mark some record from detached object as deleted and then delete it from db, but get exception "Adding a link to an entity in the Deleted state is not allowed." How can I delete this nested record from db?

    public static void UpdateCar(rentcar2.Models.Car i)
        {
            using (rentcar2.Dal.Entities db = new rentcar2.Dal.Entities())
            {
                rentcar2.Dal.Car cr = AutoMapper.Mapper.Map<rentcar2.Dal.Car>(i);
                int a = 0;
                foreach (rentcar2.Dal.CarImage c in cr.CarImages)
                {
                    c.CarId = i.Id;
                    // fl   0-old_unmodified, 1-adding, 2-deleted, 3-modified
                    switch (i.CarImages[a].fl)
                    {//try to mark record
                        case 0:
                            db.Entry(c).State = EntityState.Unchanged;
                            break;
                        case 1:
                            db.Entry(c).State = EntityState.Added;
                            break;
                        case 2:
                            **db.Entry(c).State = EntityState.Deleted;**
                            break;
                        case 3:
                            db.Entry(c).State = EntityState.Modified;
                            break;
                    }
                    a++;
                }    
                try
                {
                    **db.Cars.Attach(cr);**  // excpetion here 
                    db.Entry(cr).State = EntityState.Modified;
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    throw new System.Exception("", e);
                }
            }
        }
  • I didn't understand what's your mean? Are you looking for *Cascade Delete* https://stackoverflow.com/a/34038321/2946329 Or it's DB-side https://stackoverflow.com/a/37459049/2946329 – Salah Akbari Feb 12 '18 at 07:30
  • Just use cascades in your database and inform Entity Framework that you have a cascade on the relationship in your configuration. Also your method is long and does almost nothing. Remove the `try`/`catch` and then the `switch`, use a `Dictionary`. – Aluan Haddad Feb 12 '18 at 07:32
  • I mean that I can't to attach entity with record which marked as EntityState.Deleted for delete it from db – Konstantin Sch Feb 12 '18 at 07:38

1 Answers1

0

You first attach the entity as unchanged, then you delete it. This way, EF will understand that there is an actual state transition between the previous state (existing) to the expected new state (deleted).

grek40
  • 13,113
  • 1
  • 24
  • 50
  • @user3760744 if this answer solved your problem, you should mark it as answer ([How does accepting an answer work?](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)) – grek40 Feb 12 '18 at 18:54