Problem in Update & Delete
Posted: Wed 30 Oct 2013 08:19
Hi
I wrote a repository pattern for CRUD
insert , getAll works but when i use Delete and Update methods get errors
DELETE :
DELETE ERROR :
NEW DELETE ERROR :
UPDATE :
UPDATE ERROR :
I hope anyone help me
I wrote a repository pattern for CRUD
insert , getAll works but when i use Delete and Update methods get errors
DELETE :
Code: Select all
public T Delete<T>(T t) where T : class
{
T obj;
try
{
Set<T>().Remove(t);
SaveChanges();
obj = t;
}
catch (Exception)
{
obj = null;
}
return obj;
}
When I change Delete Method to this error changeThe object cannot be deleted because it was not found in the ObjectStateManager.
Code: Select all
public T Delete<T>(T t) where T : class
{
T obj;
try
{
Set<T>().Attach(t); // Add THIS
Set<T>().Remove(t);
SaveChanges();
obj = t;
}
catch (Exception)
{
obj = null;
}
return obj;
}
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
UPDATE :
Code: Select all
public T Update<T>(T t) where T : class
{
T obj = null;
try
{
var entry = Entry(t);
Set<T>().Attach(t);
entry.State = EntityState.Modified;
SaveChanges();
obj = t;
return obj;
}
catch (Exception)
{
return obj;
}
}
USE METHODS :Connection must be opened.
Code: Select all
var monitor = new Devart.Data.SQLite.SQLiteMonitor { IsActive = true };
Devart.Data.SQLite.Entity.Configuration.SQLiteEntityProviderConfig config = Devart.Data.SQLite.Entity.Configuration.SQLiteEntityProviderConfig.Instance;
config.Workarounds.IgnoreSchemaName = true;
var leitner = new LeitnerBoxContext();
leitner.Database.Initialize(false);
var br = new BusinessRepo<Account>(leitner);
var items = br.GetAll<Account>().ToList();
var ent1 = br.Insert(new Account { UserName = "AAA", Password = "CCC", SecurityAnswer = "E", SecurityId = 1 });
var ent2 = br.Insert(new Account { UserName = "SSS", Password = "DDD", SecurityAnswer = "F", SecurityId = 2 });
// Update ent1
var ent3 = br.Update(new Account { UserName = "TTT", Password = "GGG", SecurityAnswer = "E", SecurityId = 1 });
// Delete ent2
var ent4 = br.Delete(new Account { UserName = "SSS", Password = "DDD", SecurityAnswer = "F", SecurityId = 2 });