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.

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

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.
Because you need to use proper namespace for that!!! Shame on you for not resolving such a problem yourself.
Sorry for wrong question I was searching in System.Data.Entity namespace and replied you quickly. Thank you
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 :)
Really Thanks for you nice assistance :)
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.