TheMixy
TheMixy

Reputation: 1296

Update records using EntityFrameworkCore

I'm new to using EF to handle data in SQL. In a MVC Core project we're testing EF (Microsoft.EntityFrameworkCore, version 2.2.3) to handle data.

When trying to update data and update failed for some reason (missing fields etc) it seemed like EF actually deleted the record from the database (MSSQL 2014) instead of throwing an update error...

Is it possible?

Code for updating:

public void Update(Contact contact)
        {
            _dbContext.Update(contact);
            _dbContext.SaveChanges();
        }

Upvotes: 0

Views: 54

Answers (1)

Gabriel Llorico
Gabriel Llorico

Reputation: 1803

When trying to update data and update failed for some reason (missing fields etc) it seemed like EF actually deleted the record from the database (MSSQL 2014) instead of throwing an update error...

Is it possible?

It should not.

test it, try to debug here

_dbContext.Update(contact); 
_dbContext.SaveChanges(); 
var updated = _dbContext.Contacts.FirstOrDefault(x => x.Id == contact.Id); //debug here

check if it has a value, if still none, these are the scenarios i can think of that may have caused your problem

  • investigate the missing field specially if it is not nullable.
  • is the _dbContext used here is the same connection string used with everything?
  • is the [Key] attribute listed on your Contact entity?
public class Contact
{
    [Key]
    public int Id
}
  • overridden the SaveChanges function?
  • is what you are passing Contact contains a Key and it is not 0?
  • is a delete function called after Update?
  • try using SQL Profiler to look at the Linq to SQL if it really generated an update query and if it is really pointing at the right [Key]

but if it is still not working properly, you could do

public void Update(Contact contact)
{
    var selectedContactToBeUpdated = _dbContext.Contacts.FirstOrDefault(x => x.Id == contact.Id);

    if (selectedContactToBeUpdated != null)
    {
        selectedContactToBeUpdated.PropertyToBeUpdated1 = newValue;
        selectedContactToBeUpdated.PropertyToBeUpdated2 = newValue2;
        //additional Properties
        _dbContext.SaveChanges();
    }
}

in the scenario above, it will only generate an Update statement with fields you have changed.

Upvotes: 1

Related Questions