My requirement is that i require to delete some rows from table and then insert some in the same table. I am using Unit of work and so both deletion and insertion are part of same transaction. But when i am trying to save the data, entity framework is duplicate key throwing error. Please find below an example and code:
example:Table name- Table1, Columns - col1(c.K), col2(C.K), col3
Row To delete- 78,1,1
RowTo Add- 78,1,1 78,2,2
My Unit of Work Class:
public class DataRepository<T> : IRepository<T> where T:class // IDisposable,
{
#region Variables
private readonly CWSEntities _context;
protected readonly IDbSet<T> _dbset;
#endregion
#region Constructors
public DataRepository()
{
_context = new CWSEntities();
_dbset = _context.Set<T>();
}
public DataRepository(CWSEntities context)
{
_context =context;
_dbset = _context.Set<T>();
}
#endregion
#region Methods
public IQueryable<T> All()
{
return _context.Set<T>();
}
// public IQueryable<T> AllInclude(params Expression<Func<T,object>>[] include)
public IQueryable<T> Include(params Expression<Func<T, object>>[] include)
{
IQueryable<T> retValue = _context.Set<T>();
foreach (var item in include)
{
retValue = retValue.Include(item);
}
return retValue;
}
public T GetById(object id)
{
return this._dbset.Find(id);
}
public IEnumerable<T> Get(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
string includeProperties = "")
{
IQueryable<T> query = _dbset;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
public T Add(T entity)
{
if (entity != null)
{
return _dbset.Add(entity);
}
return null;
}
public void Delete(object id)
{
T entityToDelete = _dbset.Find(id);
Delete(id);
}
public void Delete(T entityToDelete)
{
if (entityToDelete != null)
{
if (_context.Entry(entityToDelete).State == EntityState.Detached)
{
_dbset.Attach(entityToDelete);
}
_dbset.Remove(entityToDelete);
}
}
public void Update(T entityToUpdate)
{
if (entityToUpdate != null)
{
_dbset.Attach(entityToUpdate);
_context.Entry(entityToUpdate).State = EntityState.Modified;
// _context.Entry(entity).State = System.Data.Entity.EntityState.Modified;
}
}
public virtual void Save()
{
try
{
_context.SaveChanges();
}
catch(DbEntityValidationException exception)
{
}
}
From what I can gather you are trying to add entities with the same primary key, as you said in your example
It doesn't look like your
Add
method is handling this correctly. You could first check if the entity exists by passing the primary key values of the entity and if it doesn't then do the add, if not then possibly an update?