Dougc
Dougc

Reputation: 852

Manually Updating a Many-to-Many Relationship in Entity Framework Code First

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.

Upvotes: 0

Views: 3491

Answers (1)

Slauma
Slauma

Reputation: 177153

You must map the relationships in your model as two one-to-many relationships. The additional field in the link table makes it impossible to create a many-to-many relationship. I would also recommend to use a composite key in your "link entity" TemplateFieldInstance where both components are foreign keys to the other entities. This ensures in the database that you can only have one row for a unique combination of a template field and a template and comes closest to the idea of a "many-to-many link table with additional data":

public class TemplateField
{
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    public virtual ICollection<TemplateFieldInstance> Instances { get; set; }
}

public class TemplateFieldInstance
{
    [Key, Column(Order = 0)]
    public int FieldId { get; set; }
    [Key, Column(Order = 1)]
    public int TemplateId { get; set; }

    public bool IsRequired { get; set; }

    public virtual TemplateField Field { get; set; }
    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; }
}

EF naming conventions will detect the FK relations in this model if you use the property names above.

More details about such a model type are here: https://stackoverflow.com/a/7053393/270591

Your approach to update the template is not correct: context.Entry(currentTemplate).CurrentValues.SetValues(template); will only update the scalar fields of the template, not the navigation properties nor will it add or remove any new or deleted child entities of the parent entity. Unfortunately updating detached object graphs doesn't work that easy and you have to write a lot more code, something like this:

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);

    context.Entry(currentTemplate).CurrentValues.SetValues(template);

    foreach (var currentInstance in currentTemplate.Instances.ToList())
        if (!template.Instances.Any(i => i.Id == currentInstance.Id))
            context.TemplateFieldInstances.Remove(currentInstance); // DELETE

    foreach (var instance in template.Instances)
    {
        var currentInstance = currentTemplate.Instances
            .SingleOrDefault(i => i.Id == instance.Id);
        if (currentInstance != null)
            context.Entry(currentInstance).CurrentValues.SetValues(instance);
                                                                       // UPDATE
        else
            currentTemplate.Instances.Add(instance); // INSERT
    }

    context.SaveChanges();
}

A similar example with more comments what is happening is here: https://stackoverflow.com/a/5540956/270591

Upvotes: 3

Related Questions