S
S
SMARTi2014-12-01 09:39:03
ASP.NET
SMARTi, 2014-12-01 09:39:03

Entity Framework 6 does not update foreign key in table. How to fix?

Created a simple object model with products and categories:

public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual Category Category { get; set; }
    }

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

VS helped generate the controller using odata ProductController, it contains a method to update the data:
// PUT odata/Product(5)
        public IHttpActionResult Put([FromODataUri] int key, Product product)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (key != product.Id)
            {
                return BadRequest();
            }
            
            db.Entry(product).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductExists(key))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Updated(product);
        }

The Product object comes to this method with the Category and Name changed,
but as a result, the Product Name changes in the database in the Product table, but the Category_Id does not, without any errors.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stanislav Boyarintsev, 2014-12-01
@SMARTi

To avoid problems when working with Disconnected Entities, you need to use not only Navigation Properties but also foreign key associations, for this, make your model like this:

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

More details can be found in the book "Programming Entity Framework" by Julia Lerman, page 85 section "Working with Relationships with and Without Foreign Keys"

I
issa05, 2014-12-01
@issa05

Everything is written correctly for you, create the CategoryId field, when editing this field, assign a new value - the id of another category, and save the changes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question