删除嵌套记录ef

时间:2018-02-12 07:25:12

标签: c# database entity-framework

我想将分离对象中的某些记录标记为已删除,然后将其从db中删除, 但是获得异常“不允许在”已删除“状态下添加指向实体的链接。如何从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);
                }
            }
        }

1 个答案:

答案 0 :(得分:0)

首先将实体附加为未更改,然后将其删除。这样,EF将理解在先前状态(现有)与预期新状态(已删除)之间存在实际状态转换。