I am receiving a runtime error message...... System.NullReferenceException: 'Object reference not set to an instance of an object.' at this line of code entity.ProductName = product.ProductName;
The code where the System.NullReferenceException error is occuring is inside a ASP.Net Web API project that i am calling using ajax jquery put request inside of a javascript project.
I have determined that I am receiving this System.NullReferenceException error because I am trying to update a record that I selected from the jquery datatable that has been deleted from the underlying database
I want a message that the record has been deleted please Refresh your browser or if you can think of another elegant way to end the pending transaction so that the end user won't incur an error that is fine as well. Should I check to see if the entity reference variable is null? I am just trying to figure out what is the best Practice for handling this problem. I have attached the code below. Thanks !!!
public void Put(int id, [FromBody] Product product)
{
using(BookStoresDBEntities entities=new BookStoresDBEntities())
{
try
{
var entity = entities.Products.FirstOrDefault(p => p.ProductId == id);
entity.ProductName = product.ProductName;
entity.IntroductionDate = product.IntroductionDate;
entity.Url = product.Url;
entities.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
}
}