Although the link tables which facilitate a many-to-many relationship are usually hidden by EF, I have an instance where I think I need to create (and manage) one myself:
I have the following entities:
public class TemplateField
{
public int Id
{
get;
set;
}
[Required]
public string Name
{
get;
set;
}
}
public class TemplateFieldInstance
{
public int Id
{
get;
set;
}
public bool IsRequired
{
get;
set;
}
[Required]
public virtual TemplateField Field
{
get;
set;
}
[Required]
public virtual Template Template
{
get;
set;
}
}
public class Template
{
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
public virtual ICollection<TemplateFieldInstance> Instances
{
get;
set;
}
}
So essentially; a Template
can have many TemplateField
and a TemplateField
can have many Template
.
I believe I could just add a navigation property in the form of a collection of Template
items on the TemplateField
entity and have EF manage the link entity, but I need to store some additional information around the relationship, hence the IsRequired
property on TemplateFieldInstance
.
The actual issue I'm having is when updating a Template
. I'm using code similar to the following:
var template = ... // The updated template.
using (var context = new ExampleContext())
{
// LoadedTemplates is just Templates with an Include for the child Instances.
var currentTemplate = context.LoadedTemplates.Single(t => t.Id == template.Id);
currentTemplate.Instances = template.Instances;
context.Entry(currentTemplate).CurrentValues.SetValues(template);
context.SaveChanges();
}
However; if I try and update a Template
to - for example - remove one of the TemplateFieldInstance
entities, it this throws an exception (with an inner exception) which states:
A relationship from the 'TemplateFieldInstance_Template' AssociationSet is in the 'Deleted' state. Given multiplicity constraints, a corresponding 'TemplateFieldInstance_Template_Source' must also in the 'Deleted' state.
After doing some research, it sounds like this is because EF has essentially marked the TemplateFieldInstance
foreign key to the Template
as being null and then tried to save it, which would violate the Required
constraint.
I'm very new to Entity Framework, so this is all a bit of a journey of discovery for me, so I'm fully anticipating there being errors in my approach or how I'm doing the update!
Thanks in advance.