0

I am using EF 6 and the project is using the UnitOfWork pattern.

The code I have is based on this: http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

Here is a snippet of the GenericRepository:

    public virtual void Insert(TEntity entity)
    {
        dbSet.Add(entity);
    }

    public virtual void Delete(object id)
    {
        TEntity entityToDelete = dbSet.Find(id);
        Delete(entityToDelete);
    }

    public virtual void Delete(TEntity entityToDelete)
    {
        if (context.Entry(entityToDelete).State == EntityState.Detached)
        {
            dbSet.Attach(entityToDelete);
        }
        dbSet.Remove(entityToDelete);
    }

    public virtual void Update(TEntity entityToUpdate)
    {
        dbSet.Attach(entityToUpdate);
        context.Entry(entityToUpdate).State = EntityState.Modified;
    }

What I want to do is load my Entity with no tracking, so I can then save it so it creates a duplicate version of the object and its associations etc.

I want to do this basically:

var company = DbContext.Companies.AsNoTracking()
                       .Include(c => c.Locations
                           .Select(l => l.Stores
                               .Select(s => s.Products)))
                       .Where(c => c.Id == 123)
                       .FirstOrDefault();
DbContext.Companies.Add(company);
DbContext.SaveChanges();

I'm not sure how to do this using the UnitOfWork setup that I have.

I tried to do a DbSet.Remove but that just tries to delete it, not set the tracking.

How can I do this?

cool breeze
  • 4,461
  • 5
  • 38
  • 67
  • `Context.Detach()` - see here: https://msdn.microsoft.com/en-us/library/bb896271(v=vs.100).aspx – stephen.vakil Apr 27 '16 at 20:20
  • @stephen.vakil I If I detach and attach, it will not treat the entity as a new one will it? It will try and update no? – cool breeze Apr 27 '16 at 20:26
  • @stephen.vakil my Context doesn't have Detach. It has attach and remove only: https://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext(v=vs.113).aspx – cool breeze Apr 27 '16 at 20:28
  • You should be able to access the `ObjectContext` unless anything has changed in recent versions. Check out the answer to this question: http://stackoverflow.com/questions/4168073/entity-framework-code-first-no-detach-method-on-dbcontext – stephen.vakil Apr 27 '16 at 20:48

0 Answers0