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 8783173
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T20:45:43+00:00 2026-06-13T20:45:43+00:00

I’m trying to do a simple insert with a many-to-many relationship using Entity Framework

  • 0

I’m trying to do a simple insert with a many-to-many relationship using Entity Framework 5.

I have two POCO classes as follows.

public class Category
{
    public virtual string Title { get; set; }
    public virtual DateTime EntryDate { get; set; }
    public virtual DateTime LastUpdated { get; set; }
    public virtual ICollection<Article> Articles { get; set; }
}

public class Article
{
    public virtual string Title { get; set; }
    public virtual string Content { get; set; }
    public virtual DateTime EntryDate { get; set; }
    public virtual DateTime LastUpdated { get; set; }
    public virtual ICollection<Category> Categories { get; set; }
}

And the following fluent api mapping code…

public class CategoryMap : EntityTypeConfiguration<Category>
{
    public CategoryMap()
    {
        this.ToTable("Categories");
        this.HasKey(x => x.ID);

        this.Property(x => x.Title).IsRequired().HasMaxLength(255);
    }
}

public class ArticleMap : EntityTypeConfiguration<Article>
{
    public ArticleMap()
    {
        this.ToTable("Articles");
        this.HasKey(x => x.ID);

        this.HasMany(x => x.Categories)
            .WithMany(x => x.Articles)
            .Map(x =>
            {
                x.ToTable("MapArticleCats");
                x.MapLeftKey("CategoryID");
                x.MapRightKey("ArticleID");
            });

        this.Property(x => x.Title).IsRequired().HasMaxLength(255);
        this.Property(x => x.Content).IsRequired().HasMaxLength(4000);
    }
}

The entity framework will then generate both Category and Article tables along with a third mapping table of which details were specified in the ArticleMap code (MapArticleCats), which looks like the following in SQL Server.

ArticleID – int
CategoryID -int

The following code (give or take a few lines) adds the Categories to the Article in my controller.

IEnumerable<Category> GetCats = CategoryRepository.GetAll();

//DO SOME CODE TO FIGURE WHICH CATEGORIES I NEED.
IEnumerable<Category> Categories = InferCategoriesFromPostedData(Model.Categories, GetCats);

foreach (Category c in Categories)
{
    Article.Categories.Add(c);
}

This seems to create some strange behavior on insert. It will insert a new category into the category table (DUPLICATE) and also insert the newly created CategoryID (instead of the original id) and the correct ArticleID to the MapArticleCats table.

Can anyone see where I’ve gone wrong?

  • 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-06-13T20:45:44+00:00Added an answer on June 13, 2026 at 8:45 pm

    OK what I should’ve done before submitting this article (and previous ones…massively guilty) was to search StackOverflow and bit more thoroughly.

    I found the answer to my problem here

    What was happening was nothing to do with the above code at all. It was because I was essentially injecting TWO data contexts into my controller (one in the article repository and the other in the category repository) and therefore creating duplicate records.

    ==================================================================================
    IMPORTANT EDIT
    ==================================================================================

    Just to elaborate on my answer…

    Even after doing the above fix this still didn’t solve my original issue of not being able to update the navigation properties (Categories). The fix for this is found below…

    I was model binding the entity (Article) using AsNoTracking() and this is OK if you want to just update the main entity itself but you can’t do anything with the navigation properties. e.g. adding/removing categories from the article in my case.

    This left me in a bit of a pickle as I’d tried a similar method by detaching the entity from the context, but both ways ultimately left me with the same problem of not being able to manipulate the navigation properties.

    The way to fix this was to simply just to model bind/select the entity as normal. No AsNoTracking(), no Detaching. and when attaching the entity back to the context use the following code…

        public bool Attach(T entity)
        {
            T original = _dbSet.Find(entity.ID);
            _dbContext.Entry(original).CurrentValues.SetValues(entity);
            _dbContext.Entry(original).State = EntityState.Modified;
    
            return this.Commit();
        }
    

    This way you can select it out without doing any AsNoTracking/Detaching rubbish and it will update just fine. This is OK for me, some people might find the extra trip to the db a bit offensive, but for the sake of all that grief that suits me just fine.

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

Sidebar

Related Questions

I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have just tried to save a simple *.rtf file with some websites and
I have thousands of HTML files to process using Groovy/Java and I need to
I am trying to loop through a bunch of documents I have to put
I'm making a simple page using Google Maps API 3. My first. One marker
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i

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.