0

I want to assign a list of EXISTING CHILD obj Days to Course. But Im getting pk issues or duplicated rows. Since Days can be checked or unchecked, I should remove all first and finally add all.

Course()
{
  int Id {get;set;}
  string Descripcion {get;set;}
  List<DayOfWeek> Days {get;set;}
}

DayOfWeek()
{
 int Id {get;set;}
 string Name {get;set;}
 List<Course> Courses {get;set;} //Just for Entity Framework to create the many-to-many relation
}

SOME OTHER INFO

  • code first
  • lazy loading
  • disconnected (repository/servide webapi layer, UI layer)
  • entities and dto objects, e.g. Course is mapped to UI on CourseData and viceversa.

When I Attach a new object, it is set as ADDED, I need to fix that

Fernando Torres
  • 1,070
  • 8
  • 19
  • You don't show the code you want to fix. – Gert Arnold Aug 01 '17 at 13:32
  • See [here](https://stackoverflow.com/questions/14307838/entity-framework-adding-existing-child-poco-to-new-parent-poco-creates-new-chi) and [here](https://stackoverflow.com/questions/6823947/adding-item-with-many-to-many-relationship-in-entity-framework) and post the update code you are trying. – Steve Greene Aug 01 '17 at 15:08

1 Answers1

-1

I would recommend to map your foreign key in DayOfWeek entity:

DayOfWeek()
{
 int Id {get;set;}
 int CourseId {get;set;}
 string Name {get;set;}
}

Then you can do:

context.Set<Course>().Add(course);
dayOfWeek.CourseId = course.Id;
context.Set<DayOfWeek>().Attach(dayOfWeek);
context.Entry(dayOfWeek).State = EntityState.Modified;
context.SaveChanges();

If you map your foreign keys, then your life is easier with EF.

Jan Muncinsky
  • 4,282
  • 4
  • 22
  • 40
  • Also check this post for more information: https://stackoverflow.com/questions/25441027/how-do-i-stop-entity-framework-from-trying-to-save-insert-child-objects – Jan Muncinsky Aug 01 '17 at 07:51
  • Thanks but it is a many-to-many relation.... e.g. on Monday you can have Course1 and Course2 – Fernando Torres Aug 01 '17 at 13:07
  • The M:N table is auto created by Entity Framework and it is not visible at the code level (I will add the Courses colection inside DayOfWeek for this to be clearer) thanks – Fernando Torres Aug 01 '17 at 13:28
  • Yes, but you can create your custom mapping like here: https://stackoverflow.com/questions/7050404/create-code-first-many-to-many-with-additional-fields-in-association-table – Jan Muncinsky Aug 01 '17 at 13:45