I am using EF6 and Mapster in an ASP.Net MVC project. In my Edit post controller I am trying to save the results of a data entry form. On the form there is a multiselect list box. The selections in the multiselect list box are getting passed along properly but I am not understanding the correct way to save the selected items in the multiselect list to the db. Using the code as I have it below the DisplayName property is saved but the Teams are not being saved. (the Teams table has a many to many relationship to the myRecord table)
The controller code to save the changes:
var myRecord = TypeAdapter.Adapt<MyRecord>(myRecordViewModel);
myRecord.Teams = db.Teams.Where(a => myRecordViewModel .SelectedTeamIDs.Contains(a.TeamID)).ToList();
myRecord.DisplayName = myRecordViewModel.Name;
db.Entry(myRecord).State = EntityState.Modified;
db.SaveChanges();
The myRecord class:
public class MyRecord
{
[Key]
public int Id { get; set; }
public string DisplayName { get; set; }
public virtual ICollection<Team> Teams { get; set; }
}
The Team class:
public partial class Team
{
public int TeamID { get; set; }
public string TeamName { get; set; }
public virtual ICollection<MyRecord> MyRecords{ get; set; }
}
How should this be saved to the database?