I'm trying to use the repository pattern with EntityFramework in an MVC application to update a record, but the db.SaveChanges() method isn't saving to the database. I'm not getting any errors, and I can step through the code and see the correct variables getting passed, as well as the record variable, getting updated.
Based on what I've been reading, I believe my problem is that I have two instance of my database context (MyDBEntities). The problem might be that my ReadRepository, which creates an instance of MyDBEntities is injected into the WriteRepository which also creates an instance MyDBEntities. I'm not really sure how to inject the entities into the repositories (assuming that's what I need to do).
If I try to add something like db.MyTable.Attach(record);
before db.SaveChanges()
, I'll get this error below, which makes me think I need to inject MyDBEntities()
.
An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
CONTROLLER
public class MyController : Controller
{
private IWriteRepository _writeRepository;
public MyController(IWriteRepository writeRepository)
{
_writeRepository = writeRepository;
}
[HttpPost]
public ActionResult MyPostMethod(MyViewModel model)
{
try
{
//Send to the repository to edit a record
writeRepository.EditRecord(model);
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
catch
{
throw new HttpException(500, "Internal Server Error");
}
}
}
WRITE REPOSITORY
//The ReadRepository is injected into the WriteRepository to grab records from the database
public class WriteRepository : IWriteRepository
{
private MyDBEntities db = new MyDBEntities();
private IReadRepository _readRepository;
public WriteRepository(IReadRepository readeadRepository)
{
_readRepository = readRepository;
}
public void EditRecord(MyViewModel model)
{
//Get the specific record to be updated
var record = readRepository.GetRecord(model.ID);
//Update the data
record.FirstName = model.Name;
//This isn't saving
db.SaveChanges();
}
}
READ REPOSITORY
public class ReadRepository : IReadRepository
{
private MyDBEntities db = new MyDBEntities();
//Provides the record to the write repository to edit
public MyTable GetRecord(int ID)
{
var record = (from t in db.MyTable
where t.ID == ID
select t).SingleOrDefault();
return record;
}
}