Answer the question
In order to leave comments, you need to log in
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; }
}
// 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);
}
Answer the question
In order to leave comments, you need to log in
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; }
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question