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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T06:28:14+00:00 2026-06-07T06:28:14+00:00

I have pored through StackOverflow, Google and asp.net trying to find a clear cut,

  • 0

I have pored through StackOverflow, Google and asp.net trying to find a clear cut, basic example of how to do this. All the examples have been abstract or involved complications that do not apply. I haven’t been able to extract much useful from them. So far, none of them have completely answered my question or addressed my issue(s).

I am working on an MVC project with the following model:

Article.cs:

public class Article
{

    public int ArticleId { get; set; }
    public string Title { get; set; }
    .
    .
    .
    public virtual ICollection<Category> Categories { get; set; }

    public Article()
    {
        Categories = new HashSet<Category>();
    }
}

Category.cs:

public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Article> Articles { get; set; }

    public Category()
    {
        Articles = new HashSet<Article>();
    }
}

ArticleEntities.cs:

public class ArticleEntities : DbContext
{
    public DbSet<Article> Articles { get; set; }
    public DbSet<Category> Categories { get; set; }

}

An article can have many categories and a category can belong to many articles.

So far I can save/update/create all the article fields except the Categories.

I am representing them as a checkboxes in the view. I can get the values for the selected checkboxes into the controller, but, every attempt I have made to store them in the db with the article has failed.

How do I:

1) When saving an edited article, update the existing relations in the relation table without creating duplicates?

2) When saving a new article, create the chosen relations in the relation table?

  • 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-07T06:28:16+00:00Added an answer on June 7, 2026 at 6:28 am

    I assume that you get a list of CategoryIds from the controller post action, a List<int> or more general just an IEnumerable<int>.

    1) When saving an edited article, update the existing relations in the
    relation table without creating duplicates?

    Article article; // from post action parameters
    IEnumerable<int> categoryIds; // from post action parameters
    
    using (var ctx = new MyDbContext())
    {
        // Load original article from DB including its current categories
        var articleInDb = ctx.Articles.Include(a => a.Categories)
            .Single(a => a.ArticleId == article.ArticleId);
    
        // Update scalar properties of the article
        ctx.Entry(articleInDb).CurrentValues.SetValues(article);
    
        // Remove categories that are not in the id list anymore
        foreach (var categoryInDb in articleInDb.Categories.ToList())
        {
            if (!categoryIds.Contains(categoryInDb.CategoryId))
                articleInDb.Categories.Remove(categoryInDb);
        }
    
        // Add categories that are not in the DB list but in id list
        foreach (var categoryId in categoryIds)
        {
            if (!articleInDb.Categories.Any(c => c.CategoryId == categoryId))
            {
                var category = new Category { CategoryId = categoryId };
                ctx.Categories.Attach(category); // this avoids duplicate categories
                articleInDb.Categories.Add(category);
            }
        }
    
        ctx.SaveChanges();
    }
    

    Note that the code also works when you have a ArticleViewModel instead of an Article, given that the property names are the same (SetValues takes an arbitrary object).

    2) When saving a new article, create the chosen relations in the relation
    table?

    More or less the same idea as above but simpler because you don’t need to compare with an original state in the database:

    Article article; // from post action parameters
    IEnumerable<int> categoryIds; // from post action parameters
    
    using (var ctx = new MyDbContext())
    {
        foreach (var categoryId in categoryIds)
        {
            var category = new Category { CategoryId = categoryId };
            ctx.Categories.Attach(category); // this avoids duplicate categories
            article.Categories.Add(category);
            // I assume here that article.Categories was empty before
        }
        ctx.Articles.Add(article);
    
        ctx.SaveChanges();
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have just ported an HTML site over to ASP.NET MVC 3. Google appears
Forgive me if this has been asked before. I have poured through this site
I have ported Apache Tika to Android. I have a basic question. While working
have written this little class, which generates a UUID every time an object of
I have STFW, the documentation, and poured through my own build scripts and cannot
I have this obsession with doing realtime character animations based on inverse kinematics and
I am trying to pass a file descriptor through ctypes, to a C function
I'm trying to learn OpenGL and improve my C++ skills by going through the
I am trying to learn Spring MVC by following through some of the examples
I've read through many threads and can't find anything like my issue here. 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.