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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T17:34:02+00:00 2026-05-24T17:34:02+00:00

I have a Product Model, which contains a foreign key to a ProductCategory record,

  • 0

I have a Product Model, which contains a foreign key to a ProductCategory record, and looks like this.

public class ProductModel : IProductModel
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public string ProductDescription { get; set; }
    public string ProductImagePath { get; set; }
    public decimal? PricePerMonth { get; set; }
    public bool ProductActive { get; set; }
    public ProductCategory ProductCategory { get; set; }
}

For some reason, every time a new Product is created, a new ProductCategory is also created with all of it’s values in the database being set to NULL, except for the ProductCategoryID field, which is auto generated.

In my Create view, I have a form, which contains a drop list populated with ProductCategories. Once the form is submitted, Create(Product product) Action is being called, and the new Product is being created. At this point, the new ProductCategory is also created, which is behavior that I don’t want.

My Create(Product product) Action looks like this:

    //
    // POST: /Product/Create
    [HttpPost]
    public ActionResult Create(Product product)
    {
        int productCategoryID = product.ProductCategory.ProductCategoryID;
        product.ProductCategoryID = productCategoryID;
        _productService.InsertProduct(product);
    }

… and my InsertProduct methods looks like this …

    public void InsertProduct(Product product)
    {
        Db.Products.AddObject(product);
        Save();
    }

Why is this code causing a new ProductCategory to be created every time?

EDIT: Adding table definition, in response to an answer given, whcih asked for more information:

TABLE Product (
ProductID INT PRIMARY KEY IDENTITY(1,1),
ProductCategoryID INT, -- FK to ProductCategory 
ProductName NVARCHAR(255),
ProductDescription NVARCHAR(MAX),
ProductImagePath NVARCHAR(1024),
PricePerMonth DECIMAL(7,2), -- ex 11111.11
ProductActive BIT NOT NULL DEFAULT(1)
)

TABLE ProductCategory (
ProductCategoryID INT PRIMARY KEY IDENTITY(1,1),
ProductCategoryName NVARCHAR(255),
ProductCategoryDescription NVARCHAR(MAX),
ProductCategoryActive BIT NOT NULL DEFAULT(1)
)

EDIT 2:

I still don’t understand why, exactly, but I was able to work around this problem with the following changes made to my Create(Product product) Action:

var productCategoryID = product.ProductCategory.ProductCategoryID;
product.ProductCategoryID = productCategoryID;
var newProduct = new Product
        {
            ProductName = product.ProductName,
            ProductDescription = product.ProductDescription,
            PricePerMonth = product.PricePerMonth,
            ProductImagePath = product.ProductImagePath,
            ProductCategoryID = productCategoryID
        };

_productService.InsertProduct(newProduct);

EDIT 3:

I’m still trying to wrap my head around all of this, but … I have discovered that this problem has something to do with the ProductCategory member of the Product class. From what I can tell, ModelBinding is automatically populating that property with a new ProductCategory every time the form is submitted. I can consistently avoid the problem I’ve been having here by explicitly setting Product.ProductCategory = null;

  • 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-24T17:34:03+00:00Added an answer on May 24, 2026 at 5:34 pm

    I was curious about your problem, so I got some pointers from a well-known author and trainer on MVC, and figured out the following. Key concepts are available in an MSDN blog post.

    The MVC model binding process binds the form data from the view to the model that you pass to the Create action. It finds the appropriate values in the form data to bind to the Product and ProductCategory objects, and carries out the model binding.

    The problem in your case is that the Entity Framework is not aware of the objects, because you created Product and ProductCategory objects on their own, outside of the EF context, rather than entities from the EF context. In your case, you’re using EF 4.1 with the DbContext, but this would also apply with different methods to EF 4.0 with the ObjectContext.

    Your new Product object doesn’t exist within your EF context or database — you haven’t added it yet — but your ProductCategory does. You need to map the ProductCategory object hanging off your new Product object to an existing ProductCategory from your EF entities. To do that, you can either find the existing ProductCategory by looking it up by primary key (ProductCategoryId) then assigning it to your product.ProductCategory, or you can “attach” your free-floating ProductCategory object to your entities. You pass it your ProductCategory object, and it essentially does the same thing as finding an existing entity — it looks up the entity by primary key. Both methods essentially take an existing ProductCategory object, tells the EF that your object is an entity, and sets the entity’s “state” to “Unchanged”, so when you call context.SaveChanges() it ignores the ProductCategory entity and therefore finds no changes to send back to the underlying database.

    So, before you add your Product to the EF context, you first need to A) find an existing ProductCategory entity that is already attached to EF, B) attach the detached ProductCategory object, or C) set the product.ProductCategoryId and null out the product.ProductCategory reference so the EF will find the ProductCategory for you. You chose Option C.

    Option A (Find an existing, attached entity):

    public ActionResult Create(Product product)
    {
        // find an attached entity based on primary key
        var productCat = 
            Db.ProductCategories.Find(product.ProductCategory.ProductCategoryId); 
        product.ProductCategoryId = productCat.ProductCategoryId;
        product.ProductCategory = productCat;
        _productService.InsertProduct(product);
    }
    

    Option B (Attach a detached entity):

    public ActionResult Create(Product product)
    {
        // attach an entity - EF will find the entity to attach using the entity's primary key
        Db.ProductCategories.Attach(product.ProductCategory); 
        product.ProductCategoryId = product.ProductCategory.ProductCategoryId;
        _productService.InsertProduct(product);
    }
    

    Option C (Null out the entity reference):

    public ActionResult Create(Product product)
    {
        product.ProductCategoryId = product.ProductCategory.ProductCategoryId;
        product.ProductCategory = null;
        _productService.InsertProduct(product);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have models like this: class Vendor(models.Model): title = models.CharField() class Product(models.Model): ... vendor
i've a problem with my tabularinline field. I have model like this class Product(models.Model):
I'm using Doctrine ODM with MongoDB. I have a product model like this: namespace
For example I have data model like this Entity: Store Entity: Inventory Entity:Product Attribute:
I have a data model which contains an array of Product objects. Before reporting
I have a Home ViewModel class which contains others class: public class HomeVM {
In Django, I have two models: class Product(models.Model): name = models.CharField(max_length = 50) categories
Given a model like this ProductFacets contains the following data: ProductId, FacetTypeId 1, 1
I have the following models: class Product < ActiveRecord::Base belongs_to :brand belongs_to :model accepts_nested_attributes_for
I have one list, which the item render it`s like this: link . But

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.