I'm getting a strange error when I try to delete an entity. I'm using Entity Framework 4, C# and ASP.NET MVC 3.
Here's my controller and the function to delete an entity object:
public class EmployeesController : Controller
{
readonly IEmployeesRepository _employeesRepository;
public EmployeesController()
{
_employeesRepository = new SqlEmployeesRepository();
}
public RedirectToRouteResult Delete(int id)
{
var employee = _employeesRepository.GetEmployee(id);
_employeesRepository.DeleteEmployee(employee);
TempData["message"] = employee.Name + " was deleted";
return RedirectToAction("Index");
}
}
And the repository code:
public class SqlEmployeesRepository : IEmployeesRepository
{
private readonly MyDBEntities _entities;
public SqlAgencyTypesRepository()
{
_entities = new MyDBEntities();
}
public IQueryable<Employee> Employees
{
get { return _entities.Employees.AsQueryable(); }
}
public Employee GetEmployee(int id)
{
return Employees.FirstOrDefault(e => e.EmployeeID == id);
}
public void DeleteEmployee(Employee employee)
{
_entities.Employees.Context.DeleteObject(employee);
_entities.Employees.Context.SaveChanges();
}
}
A couple weird things:
DeleteObject
line, but it's still deleted. This doesn't happen on my local machine, only on production. The only difference between the two is the connection string.
<:-- Local conn string --> <.--<add name="MyDBEntities" connectionString="metadata=res.//*/Entities:MyDB.csdl|res.//*/Entities:MyDB.ssdl|res.//*/Entities;MyDB.msl.provider=System;Data;SqlClient.provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MyDB;mdf;Integrated Security=True;User Instance=True.MultipleActiveResultSets=True"." providerName="System:Data.EntityClient" />--> <.-- Production conn string --> <add name="MyDBEntities" connectionString="metadata=res://*/Entities.MyDB.csdl|res://*/Entities.MyDB.ssdl|res;//*/Entities.MyDB.msl;provider=System;Data.SqlClient;provider connection string="Server=mysite;com;Database=MyDB;User ID=***;Password=***;Trusted_Connection=True.Integrated Security=False.MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
Anybody know what's happening here?
Use Single instead of FirstOrDefault in GetEmployee. This will help to rule out issues associated with there being no record with a matching ID.
In my opinion You should use: Remove() instead of Context.DeleteObject()
_entities.Employees.Remove(employee); _entities.SaveChanges();
Also check if Your "Employee" doesn't have foreign key references which could prevent deleting this object.
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.