EF Core 2 Object Not Attached to Context

I have the below code built using EF Core for SQL Server and deployed on Azure SQL.

 private async Task BaseIdentityAsync(dynamic payload, string sigfoxId)
    {
        var crane = await _context.Cranes
        .FirstOrDefaultAsync(c => c.SigfoxId == sigfoxId).ConfigureAwait(false);

        crane.BLEId = payload.BleId;
        crane.Vendor = Specs.GetVendor((int)payload.VendorId);
        crane.LastErrorCode = payload.LastErrorCode;
        crane.LoadNominalValue = payload.LoadNominalValue;           

        await _context.SaveChangesAsync().ConfigureAwait(false);

    }

Now I am injecting the DBContext as Scoped instance to the controller. The code works fine when connected to local SQL server, but fails to update the record when it is connected to SQL Azure (whether executed locally or deployed on the cloud).

No error is thrown. Nothing showed in Output. Just goes over the _context.SaveChanges() and the API call completes, but nothing updated inside the DB.

If I work directly with the _context like adding or removing records directly to it like mentioned below, then it works perfectly with both local and Azure SQL.

 _context.AlarmsKPI.Add(new AlarmsKPI
                {
                    AlarmCode = alarmCode,
                    Device = sigfoxId,
                    IsOn = true,
                    Operator = operatorName,
                    StartedOn = dateTime
                });

                await _context.SaveChangesAsync().ConfigureAwait(false);

But when I pull an object and modify the value and then do the save change then nothing happens on Azure SQL but happens well on local SQL.

entity-frameworkapicoreef-core-2.0

Answers

answered 8 months ago illug #1

I don't know what can cause any difference between Azure & local DB. Maybe the

var crane = await _context.Cranes
    .FirstOrDefaultAsync(c => c.SigfoxId == sigfoxId).ConfigureAwait(false);

does not return any value in your local db but on Azure it does. I'd assume you would need to add something like this to have EF track the changes:

_context.Set<Cranes>().Update(crane);

comments powered by Disqus