I have code that is working to add new row into my site profile table but when someone tries to update the profile, I am not sure how to handle that. I am updating multiple tables from the controller.

I have following code. I check in customers table if ID is already present, if yes, then I change the state of entity to be modified.(I found this code online). I have commented out the next line because it was giving me an error.

This code does not throw any error on saving changes but it does not update the database.

    var oldCustomer = _context.Customers.Find(objSv.CustomerServices.strUserID);
     var oldCustomerServices = _context.CustomerServices;

    if (oldCustomer == null) {
      _context.Customers.Add(obj);
      _context.CustomerServices.Add(objSv.CustomerServices);
        }
     else
     {
       _context.Entry(oldCustomer).State = EntityState.Modified;
 //  _context.Entry(oldCustomerServices).State = EntityState.Modified;
            }

   _context.SaveChanges();

I would like database to be updated with new object. These are my new objects with new data

        CustomerProfile obj = GetCustomerProfile();
        ServiceProvider objSv = GetServiceProvider();`enter code here`

1 Answers

0
TanvirArjel On

Problem is in the following line:

var oldCustomerServices = _context.CustomerServices;

Here _context.CustomerServices is not a CustomerServices object. Its a DbSet of CustomerService but you are treating like a CustomerServices object.

I think your code should be as follows:

var oldCustomerServices = _context.CustomerServices.Find(CustomerServices.Id); // <-- I have assumed primary key name of `CustomerServices` is `Id`. If anything else then use that.

if(oldCustomerServices == null)
{
    CustomerServices newCustomerServices = new CustomerServices()
    {
      // Populate the customer service property here
    }
    _context.CustomerServices.Add(newCustomerServices);
} 
else
{
     _context.Entry(oldCustomerServices).State = EntityState.Modified;
}


var oldCustomer = _context.Customers.Find(objSv.CustomerServices.strUserID);

if (oldCustomer == null) 
{
   Customer newCustomer = new Customer()
   {
       // Populate the customer property here
   }

   _context.Customers.Add(newCustomer);
  _context.CustomerServices.Add(objSv.CustomerServices);
}
else
{
  _context.Entry(oldCustomer).State = EntityState.Modified;
}

_context.SaveChanges();