I’m pretty new to Entity Frameworks.
I have a set of Static Data which includes the following:
Templates, which have a Many To Many relationship with Columns
I want to create a new UserReport which has a reference to an existing Template, and a subset of the Columns associated with the said same template.
I expect to save the UserReport record, and a series of records in a UserReportColumns mapping table linking the UserReport to existing columns.
My code is as follows:
ReportTemplate template = staticData.ReportTemplates.First();
UserReport newReport = new UserReport()
{
....
Columns = FilterColumns(template.Columns)
....
}
....
context.UserReports.Attach(userReport);
context.UserReports.AddObject(userReport);
context.SaveChanges();
This attempts to recreate everything in the object hierarchy in the database.
How can I get it so that it only saves the UserReport and the UserReport_Column links?
You are retrieving the
templatefrom a differentDbContextinstance(or some cached data source). Hence thecontextassumes that the template and the columns are new objects.To overcome this problem you have to attach the existing objects to the context to avoid EF adding them to the database.