Using Web API 2 and EF 6.1 code first.
I am trying to add a new Template
(see model) which has relationships to already existing TimePeriods
and Stations
.
public class Template
{
public int TemplateID { get; set; }
public string Name { get; set; }
public List<TimePeriod> TimePeriods { get; set; }
public List<Station> Stations { get; set; }
}
public class Station
{
public int StationID { get; set; }
public string Name { get; set; }
public List<Template> Templates { get; set; }
}
public class TimePeriod
{
public int TimePeriodID { get; set; }
public TimeSpan From { get; set; }
public TimeSpan To { get; set; }
public List<Template> Templates { get; set; }
}
The new template object contains a list of Station
and a list of TimePeriod
with correct IDs/primary keys. I hoped that EF would recognize that the related entities were already existing by looking att their primary keys but it seems not. Instead, all the related entities are added again resulting in duplicates.
private SchedulingContext db = new SchedulingContext();
[ResponseType(typeof(Template))]
public IHttpActionResult PostTemplate(Template template)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Templates.Add(template);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = template.TemplateID }, template);
}
Does this have something to do with me using a new context? If so, how can I prevent this behavior?
Solution thanks to Evandro:
public void PostTemplate(Template template)
{
db.Templates.Add(template);
foreach (var item in template.Stations)
{
db.Entry<Station>(item).State = EntityState.Unchanged;
}
foreach (var item in template.TimePeriods)
{
db.Entry<TimePeriod>(item).State = EntityState.Unchanged;
}
db.SaveChanges();
}