I want to insert or update a row in a table with Entity Framework depending if the primary key (string) already exists in the table.
I am using the following code to do that which I got from here: Insert or update pattern
private void InsertOrUpdate(ServiceMonitoring sm)
{
    try
    {
        using (var context = new MyDBEntities())
        {
            context.Entry(sm).State = sm.serviceName == null ?
                EntityState.Added :
                EntityState.Modified;
            context.SaveChanges();
        }
        log.Info("ServiceMonitoring updated");
    }
    catch (Exception ex)
    {
        log.Error("Error updating ServiceMonitoring");
        log.Debug(ex.Message);
    }
}
It is working fine when the row (e.g. serviceName = "MyService") already exists. Then an UPDATE is performed. But if the row does not exist, the INSERT fails and I get the following error message:
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded.
Any help is highly appreciated!
 
    