简体   繁体   中英

LINQ to Entities DeleteAllOnSubmit throws Unknown Method

I'm re-writing an app that used to use LINQ to SQL DeleteAllOnSubmit and am now using LINQ to Entities in an MVC5 application. MSDN showed the way to structure my L2E code. However, I receive Unknown Method for the following snippet:

IEnumerable<QuoteItem> quoteItemsToDelete = (from qi in QuoteItem
where qi.QuoteID = q.QuoteID
select qi).ToList();
QuoteItem.DeleteAllOnSubmit(quoteItemsToDelete);
SubmitChanges();

The L2S snippet I'm trying to replace is as follows:

    HttpContext.Current.GetDataContext().QuoteItems.
    DeleteAllOnSubmit<QuoteItem>(q.QuoteItems);

Based on comments received, I modified the code as follows:

using (var ctx = new FreightEntities())
        {
            var quoteitemtoDelete = ctx.QuoteItems.Remove();
            ctx.SaveChanges();
        }

However, this causes Unknown Method Remove() of System.Data.Entity.DbSet

How should I modify my L2E code to accomplish the same purpose as the L2S syntax?

Something on following lines should work for you:

    public void DeleteAllOnSubmit<T>(IEnumerable<T> items) where T : class
    {
        foreach (var item in items)
        {
            Set<T>().Attach(item);
            Set<T>().Remove(item);
        }

        SaveChanges();
    }

Basically you will have to loop through each item and call Remove passing single item at a time.

To know more about Remove method refer DbSet.Remove()

With EF Code First all you need to delete an entity is to attach it and set its state to Deleted. This is demonstrated Delete Entity using DBContext

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM