Entity Framework: how to change existing integer foreign key value in an Entity?

c# entity-framework-6


This should be a simple Entity Framework 6 question: How can I change a foreign key field value from 3 to 5 and successfully save to a Microsoft SQL Server database? My code saves other fields in the same record successfully, but does not change the foreign key field value from 3 to 5 (it remains 3 without error.)

More info:

I have a nested relation between OrderLine and Product where OrderLine is a many-to-one to Product (Product is the parent table which could be null in OrderLine.) OrderLine has an integer foreign key field that refers to the Product productid. Entity Framework also has the Product relation in OrderLine too in this POCO:

public class OrderLine {
    public int orderid     {get;set;}
    public int productid   {get;set;} // Foreign Key to Product
    public int quantity    {get;set;}
    public Product product {get;set;} // generated by Entity Framework relation
public class Product {
    public int productid   {get;set;}

When I change OrderLine.productid to a different value, it simply does not save the value but does modify other fields successfully like quantity. OrderLine is EntityState.Modified and Product is Unchanged (because we're not modifying Product, just referring to a different one.)

What am I missing? Do I need to set the Entity Framework Product relation to null to get productid to save or how should the code below change to allow the save? I would like to simply change the productid value rather than load the entire Product record from the database just to change the id value.

orderLine.productid = 5;
orderLine.quantity = orderLine.quantity++;
DbContext.Entry(orderLine).State = EntityState.Modified;
// quantity increments by one and persists, productid stays 3.


When I add the code to set the Product relation to null product = null before saving, it successfully saves and refers to the other product. I use ASP.NET MVC data binding to get an ICollection<OrderLine> orderLines initially in the Controller.

So strange. Product product was Unchanged so I guess Entity Framework decides to skip the field productid because the Product data was present? When setting Product product to null then it decides to allow the productid field to change?

1/31/2018 9:12:13 PM

Popular Answer

If you point to another FK object you either need to change the Id and remove the reference to the navigation object or you have to update both the Id and the navigation object. However, normally, if you change one and not the other, EF will throw an exception about it. I wonder if you have that setting turned off, like did you turn off ValidateOnSaveEnabled?

2/2/2018 4:40:28 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow