Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7621341
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T04:10:21+00:00 2026-05-31T04:10:21+00:00

Although the link tables which facilitate a many-to-many relationship are usually hidden by EF,

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T04:10:22+00:00Added an answer on May 31, 2026 at 4:10 am

    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

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the tables question, topic and question_has_topic (many-to-many relationship). In my application admins
I have a model which contains a link to sql query that fetches information
In my Rails 3 application I have a simple model relationship which is as
I have a problem with using EF 4.1 and many to many relationship. I
I have two tables: - Attendees - Events Normally, I would create a mapping
I have an app where I want to link an instance of a model
Although this code is from an algorithm text, I have a bit of a
Although appengine already is schema-less, there still need to define the entities that needed
Although I have found some solutions to this problem, none of them refer to
Although I have set pyramid.reload_templates to true e.g. pyramid.reload_templates = true , each time

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.