i have implemented the Generic Repository Pattern in my app , with unity container as DI provider but when i start testing if it works or not this error appear " An entity object cannot be referenced by multiple instances of IEntityChangeTracker "
my Repository Code
public interface IRepository<T> where T : class
{
IEnumerable<T> GetAll();
T Get(int id);
T Add(T item);
bool Update(T item);
bool Delete(T item);
IEnumerable<T> Find(Func<T, bool> predicate);
void Save();
}
public class Repository<M, T> : IRepository<T> where T : class where M : DbContext, new()
{
private ILogger _Log;
public Repository(ILogger log)
{
_Log = log;
}
private M _entities = new M();
public M Context
{
get { return _entities; }
set { _entities = value; }
}
public T Add(T item)
{
try
{
_entities.Set<T>().Add(item);
return null;
}
catch (Exception ex)
{
_Log.LogErorr(this.GetType().Name + "Add Method", ex.Message + "--" + ex.InnerException);
throw;
}
}
public virtual bool Delete(T item)
{
try
{
_entities.Set<T>().Remove(item);
return true;
}
catch (Exception ex)
{
_Log.LogErorr(this.GetType().Name + "Delete Method", ex.Message + "--" + ex.InnerException);
throw;
}
}
public IEnumerable<T> Find(Func<T, bool> predicate)
{
IEnumerable<T> query = _entities.Set<T>().Where(predicate);
return query;
}
public T Get(int id)
{
return _entities.Set<T>().FirstOrDefault();
}
public IEnumerable<T> GetAll()
{
IEnumerable<T> data = _entities.Set<T>();
return data;
}
public bool Update(T item)
{
try
{
_entities.Entry(item).State = EntityState.Modified;
return true;
}
catch (Exception ex)
{
_Log.LogErorr(this.GetType().Name + "Update Method", ex.Message + "--" + ex.InnerException);
throw;
}
}
public virtual void Save()
{
try
{
_entities.SaveChanges();
}
catch (Exception ex)
{
_Log.LogErorr(this.GetType().Name + "Save Method", ex.Message + "--" + ex.InnerException);
throw;
}
}
}
}
then i try to add some dummy data to the DB by this code and inject the controller with service
public class HomeController : Controller
{
private IRepository<account> _AccountRepository;
public HomeController(ILogger Log,
IRepository<account> AccountRepository)
{
_Log = Log;
_AccountRepository = AccountRepository;
}
account ac = new account()
_AccountRepository.Add(ac);
_AccountRepository.Save();
}
Aucun commentaire:
Enregistrer un commentaire