Reputation: 383
//Repository Method
public void Delete(int id)
{
using (var scope = new UnitOfWork(_container))
{
var entity = AuthorService.GetById(id);
scope.Container.Authors.DeleteObject(entity);
}
}
Ninject binding
public class LibraryManagerInjectModule : NinjectModule
{
public override void Load()
{
Bind<LibManagerContainer>().To<LibManagerContainer>().InThreadScope();
}
}
//Author Service Class
public static class AuthorService
{
private static LibManagerContainer Container
{
get { return MF.MF.Get<LibManagerContainer>(); }
}
public static Author GetById(int id)
{
using (var scope = new UnitOfWork(Container))
{
return Container.Authors.SingleOrDefault(x => x.Id == id);
}
}
public static Author GetByName(String name)
{
using (var scope = new UnitOfWork(Container))
{
return Container.Authors.SingleOrDefault(x => x.Name == name);
}
}
}
Using this code i m not able to delete the entity from database. it show me an error that entity not belong to same object state manager but i create the libContainer object inThreadscope but never able to delete the entity.
Upvotes: 0
Views: 213
Reputation: 12846
The DataContext
you use to retrieve the entity
tracks the entity, to be aware of changes to it. Because of that, you are not able to save entities retrieved from one DataContext
(or UnitOfWork
in your case) using another.
As you mentioned in the comments, deleting should be another transaction. To achieve this you should delete by id, not the object.
Just add a RemoveById
method to AuthorService
:
public static class AuthorService
{
...
public static void RemoveById(int id)
{
using (var scope = new UnitOfWork(Container))
{
var author = Container.Authors.SingleOrDefault(x => x.Id == id);
Container.Authors.Remove(author);
}
}
...
Upvotes: 1
Reputation: 25019
You don't need to load entity from db to delete record. Id
is enough to know, and it resolves another context problem:
var employer = new Employ { Id = 1 };
ctx.Employ.Attach(employer);
ctx.Employ.Remove(employer);
ctx.SaveChanges();
Taken from here: Delete a single record from Entity Framework?
P.S. Something wrong with your architecture. A single context should be used within one scope.
Upvotes: 2