0

i use this code for delete records in entity framework(several record)

var tag = from t in objLib.TagsField where t.Book_ID_FK == id select t;
            foreach (var t in tag)
            {
                objLib.TagsField.Context.DeleteObject(t);
                objLib.SaveChanges();
            }

how i delete it without use for each this code ( it Takes time!!)

0

3 Answers 3

1

You just call the SaveChanges afterwards:

var tag = from t in objLib.TagsField where t.Book_ID_FK == id select t;
        foreach (var t in tag)
        {
            objLib.TagsField.Context.DeleteObject(t);
        }
 objLib.SaveChanges();
Sign up to request clarification or add additional context in comments.

Comments

0

Deleting with LINQ will bring all the rows you're deleting into memory. If they aren't in memory already, it will be faster to issue a SQL statement to delete the rows from the database.

Other than that, I would try Davids answer, since EF can bacth the updates together... I guess that also would improve perf some.

Comments

0

I used this to achieve the same thing...and I am using Entity Framework 5. I know the Using() block can be used now and is recommended - but here are the basic commands that work for me for just adding some alternatives:

/// <summary>
/// Method that will remove a favorite from the tblfavorite table.
/// </summary>
/// <param name="favoriteID"></param>
/// <returns></returns>
public Boolean DeleteFavoriteByFavoriteID(Int32 favoriteID)
{
    //Assume not found.
    IsFound = false;

    //Query the DB.
    var MatchedRec = (from f in dbContext.tblfavorites
                      where f.FavoriteID == favoriteID
                      select f).FirstOrDefault();

    //See if anything was found.
    if (MatchedRec != null)
    {
        IsFound = true;

        dbContext.tblfavorites.Remove(MatchedRec);
        dbContext.SaveChanges();
        return true;
    }

    //Default.
    return false;
}

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.