I'm new to Entity Framework so please bear with me.
I have these entities in my DAL
public class TimeSheet
{
[Key]
public int TimeSheetID { get; set; }
public DateTime SignIn { get; set; }
public DateTime SignOut { get; set; }
public virtual ICollection<TimeSheetDetail> TimeSheetDetails { get; set; }
}
public class TimeSheetDetail
{
[Key]
public int TimeSheetDetailID { get; set; }
public string Description { get; set; }
}
And I got the following error (Attaching an entity of 'Model' failed because another entity of the same type already has the same primary key value) when trying to Update the record, my update code below :
public class TimeSheetService : ITimeSheetService
{
private readonly IRepository<TimeSheet> _repo;
private readonly IRepository<TimeSheetDetail> _repo2;
public void EditTimeSheet(TimeSheet obj)
{
_repo.Update(obj); //Update TimeSheet <-- error here
//loop TimeSheetDetails
foreach (var item in obj.TimeSheetDetails)
{
//Insert
if (_repo2.GetById(item.TimeSheetDetailID) == null)
{
_repo2.Insert(item);
}
//Update
else
{
_repo2.Update(item);
}
}
foreach (var item in _repo.GetById(obj.TimeSheetID).TimeSheetDetails)
{
//Delete
if (!obj.TimeSheetDetails.Any(w => w.TimeSheetDetailID == item.TimeSheetDetailID))
{
_repo2.Delete(item.TimeSheetDetailID);
}
}
}
}
My generic repository :
public void Insert(T obj)
{
_dbSet.Add(obj);
}
public void Update(T obj)
{
_dbSet.Attach(obj);
_dbContext.Entry(obj).State = EntityState.Modified;
}
public void Delete(T obj)
{
_dbSet.Remove(obj);
}
I've looked around and got a mixed answer. So my question is :
- How to achieve this?
- Is this an acceptable way to do this? Is there any other simpler way?
Any help will be appreciated.