c# - Entity Framework 6 - How to update entities with Collection child properties -


i'm new entity framework please bear me.

i have these entities in 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 got following error (attaching entity of 'model' failed because entity of same type has same primary key value) when trying update record, 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 , got mixed answer. question :

  1. how achieve this?
  2. is acceptable way this? there other simpler way?

any appreciated.


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -