7

I'm trying to delete an object in my asp.net MVC3/Code-first Entity Framework application, but I don't seem to have the necessary options, as it brings up a "does not contain a definition for DeleteObject" error. Anyone know if I'm missing an assembly reference. Here is my repository code:

private dbContext db = new dbContext();

public void DeleteAccessDetails(AccessDetails details)
{
     db.DeleteObject(details); //error here as DeleteObject isn't recognised
}

Here are my references:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySite.Models;
using System.Data;
using System.Data.Objects;
using System.Web.Mvc;
using System.Data.Entity;

I thought having System.Data.Entity would have been enough to bring up DeleteObject, but intellisense is hardly bringing up any options - only Dispose, Entry, SaveChanges and Set

Edit: Here is also my code for accessing the repository:

Repository rep = new Repository();
AccessDetails paymentUpdate = rep.GetPaymentByID(item.AccessDetailsTableID);
rep.DeleteAccessDetails(paymentUpdate);

Edit 2: Here is an image of my references folder:

enter image description here

Thanks

tereško
  • 58,060
  • 25
  • 98
  • 150
e-on
  • 1,547
  • 8
  • 32
  • 65
  • Right enough, I don't have System.Data.Objects in my references folder. When I looked in the Add Reference section (.NET tab) it wasn't there. – e-on Jul 20 '11 at 15:30

4 Answers4

25

DbContext does not have a DeleteObject() method. Instead of that, use the Remove() method to clear the object from the DbSet, then save the changes.

dbContext db = new dbContext(); // Arrange the context

Department dept = db.Departments.Single(p => p.Id == "1"); // Find the item to remove

db.Departments.Remove(dept); // Remove from the context

b.SaveChanges(); // Delete from the database
Matthew Haugen
  • 12,916
  • 5
  • 38
  • 54
Fakeer
  • 251
  • 3
  • 2
4

The documentation for the DbContext in EF4.1 seems to show that it doesn't include a delete method on that class: http://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext(v=vs.103).aspx...

This question looks similar - might be some help: MVC 3 EF 4.1 dbContext - Deleting one-to-many data object with non-nullable foreign-key relation

Community
  • 1
  • 1
Dave
  • 3,581
  • 1
  • 22
  • 25
0

You can use this format:

context.Entry(temp).State = EntityState.Deleted;  

Remove() only work in DBContext..

Diego Venâncio
  • 5,698
  • 2
  • 49
  • 68
0

In Mvc 5 use RemoveRange instead of DeleteObject while deleting list.

RemoveRange();