1

I am new in Entity Framework. I want to remove multiple entities in one database context. If I used DBContext.Remove(Object) then It delete only the one entity from database. Please consider my code:

            CCSRequest objCCSRequest = DBContext.CCSRequest.Find(ccsRequestId);
            if (objCCSRequest != null)
            {
                DBContext.CCSRequest.Remove(objCCSRequest);
                DBContext.SaveChanges();
            }
            CCProducts objCCProducts = DBContext.CCProducts.Find(ccsRequestId);
            if (objCCProducts != null)
            {                    
                DBContext.CCProducts.Remove(objCCProducts);
                DBContext.SaveChanges();
            }

I want to remove entity in both CCSRequest and CCProducts table. Thank you in advance.

Samar
  • 35
  • 1
  • 1
  • 10

2 Answers2

0

Going by the answer to a similar question, you will need to do this in a loop. Please check the answer to this question:

how to delete multiple rows of data with linq to EF using DbContext

Community
  • 1
  • 1
0

If you want to have a loop that will remove entities of different types you might use this:

object[] entities = new object[]{
    DBContext.CCSRequest.Find(ccsRequestId),
    DBContext.CCProducts.Find(ccsRequestId)
};
foreach(object entity in entities)
{
    DBContext.Entry(entity).State = EntityState.Deleted;
}
mr100
  • 4,340
  • 2
  • 26
  • 38
  • Yes, I want to remove entities with different types not a same type. The problem is when I use EntityState.Deleted the i found some error like "The name EntityState" does not exist in the current context". I am using Entity Framework 4.0. Thank you for your assistance. – Samar Jun 14 '14 at 07:46
  • Because you need to use proper namespace for that!!! Shame on you for not resolving such a problem yourself. – mr100 Jun 14 '14 at 07:52
  • Sorry for wrong question I was searching in System.Data.Entity namespace and replied you quickly. Thank you – Samar Jun 14 '14 at 08:29
  • You're welcome. We are here not for providing whole ready-to-use code but instead to help solve some problems. When you ask question you should as well show some effort :) – mr100 Jun 14 '14 at 08:37
  • Really Thanks for you nice assistance :) – Samar Jun 14 '14 at 08:46