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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T01:07:58+00:00 2026-06-01T01:07:58+00:00

I made a small project with Northwind database to illustrate the problematic. Here is

  • 0

I made a small project with Northwind database to illustrate the problematic.

Here is the action of the controller :

[HttpPost]
public ActionResult Edit(Product productFromForm)
{
    try
    {
        context.Products.Attach(productFromForm);
        var fromBD = context.Categories.Find(productFromForm.Category.CategoryID);
        productFromForm.Category = fromBD;
        context.Entry(productFromForm).State = EntityState.Modified;
        context.SaveChanges();
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

context is instanced in the constructor of the Controller as new DatabaseContext().

public class DatabaseContext:DbContext
{
    public DatabaseContext()
        : base("ApplicationServices") {
        base.Configuration.ProxyCreationEnabled = false;
        base.Configuration.LazyLoadingEnabled = false;
    }

    public DbSet<Product> Products { get; set; }
    public DbSet<Category> Categories { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder){

        modelBuilder.Configurations.Add(new ProductConfiguration());
        modelBuilder.Configurations.Add(new CategoriesConfiguration());
    }

    private class ProductConfiguration : EntityTypeConfiguration<Product> {
        public ProductConfiguration() {
            ToTable("Products");
            HasKey(p => p.ProductID);
            HasOptional(p => p.Category).WithMany(x=>x.Products).Map(c => c.MapKey("CategoryID"));
            Property(p => p.UnitPrice).HasColumnType("Money");
        }
    }

    private class CategoriesConfiguration : EntityTypeConfiguration<Category> {
        public CategoriesConfiguration() {
            ToTable("Categories");
            HasKey(p => p.CategoryID);
        }
    }
}

public class Category {
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
    public string Description { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

public class Product {
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public string QuantityPerUnit { get; set; }
    public decimal UnitPrice { get; set; }
    public Int16 UnitsInStock { get; set; }
    public Int16 UnitsOnOrder { get; set; }
    public Int16 ReorderLevel { get; set; }
    public bool Discontinued { get; set; }
    public virtual Category Category { get; set; }
}

The problem is that I can save anything from the Product but not the change of the category.

The object productFromForm contains the new CategoryID inside productFromForm.Product.ProductID without problem. But, when I Find() the category to retrieve the object from the context I have an object without Name and Description (both stay to NULL) and the SaveChanges() doesn’t modify the reference even if the ID has changed for the property Category.

Any idea why?

  • 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-01T01:08:00+00:00Added an answer on June 1, 2026 at 1:08 am

    Your (apparently) changed relationship doesn’t get saved because you don’t really change the relationship:

    context.Products.Attach(productFromForm);
    

    This line attaches productFromForm AND productFromForm.Category to the context.

    var fromBD = context.Categories.Find(productFromForm.Category.CategoryID);
    

    This line returns the attached object productFromForm.Category, NOT the object from the database.

    productFromForm.Category = fromBD;
    

    This line assigns the same object, so it does nothing.

    context.Entry(productFromForm).State = EntityState.Modified;
    

    This line only affects the scalar properties of productFromForm, not any navigation properties.

    Better approach would be:

    // Get original product from DB including category
    var fromBD = context.Products
        .Include(p => p.Category)  // necessary because you don't have a FK property
        .Single(p => p.ProductId == productFromForm.ProductId);
    
    // Update scalar properties of product
    context.Entry(fromBD).CurrentValues.SetValues(productFromForm);
    
    // Update the Category reference if the CategoryID has been changed in the from
    if (productFromForm.Category.CategoryID != fromBD.Category.CategoryID)
    {
        context.Categories.Attach(productFromForm.Category);
        fromBD.Category = productFromForm.Category;
    }
    
    context.SaveChanges();
    

    It becomes a lot easier if you expose foreign keys as properties in the model – as already said in @Leniency’s answer and in the answer to your previous question. With FK properties (and assuming that you bind Product.CategoryID directly to a view and not Product.Category.CategoryID) the code above reduces to:

    var fromBD = context.Products
        .Single(p => p.ProductId == productFromForm.ProductId);
    context.Entry(fromBD).CurrentValues.SetValues(productFromForm);
    context.SaveChanges();
    

    Alternatively you can set the state to Modified which would work with FK properties:

    context.Entry(productFromForm).State = EntityState.Modified;
    context.SaveChanges();
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

this is my first question here. I've made a small quiz project about the
Ok so I have a small project with two different scaffoldings I've made.In the
A recent project made use of very pixel-large (~5e3px2) but still byte-small (~100kb —
I am working on a small iOS project, with a UITableView. I made a
I made a small change to my wpf project and all of a sudden
So I made a program with WPF, C# and WMI as a small project
I use LINQ to SQL in a WPF project. I have made small changes
I made a small database(1 table) in phpMyAdmin. One of the fields I want
I made small program to divide large pictures and take part of them. When
I made a small winforms application to monitor a certain folder for new pdf

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.