Entity Framework 5 Updating a Record

Entity Framework 5 Updating a Record

You are looking for:

db.Users.Attach(updatedUser);
var entry = db.Entry(updatedUser);
entry.Property(e => e.Email).IsModified = true;
// other changed properties
db.SaveChanges();

How to update record using Entity Framework Core?

To update an entity with Entity Framework Core, this is the logical process:

  1. Create instance for DbContext class
  2. Retrieve entity by key
  3. Make changes on entity's properties
  4. Save changes

Update() method in DbContext:

Begins tracking the given entity in the Modified state such that it will be updated in the database when SaveChanges() is called.

Update method doesn't save changes in database; instead, it sets states for entries in DbContext instance.

So, We can invoke Update() method before to save changes in database.

I'll assume some object definitions to answer your question:

  1. Database name is Store

  2. Table name is Product

Product class definition:

public class Product
{
public int? ProductID { get; set; }

public string ProductName { get; set; }

public string Description { get; set; }

public decimal? UnitPrice { get; set; }
}

DbContext class definition:

public class StoreDbContext : DbContext
{
public DbSet<Product> Products { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Your Connection String");

base.OnConfiguring(optionsBuilder);
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>(entity =>
{
// Set key for entity
entity.HasKey(p => p.ProductID);
});

base.OnModelCreating(modelBuilder);
}
}

Logic to update entity:

using (var context = new StoreDbContext())
{
// Retrieve entity by id
// Answer for question #1
var entity = context.Products.FirstOrDefault(item => item.ProductID == id);

// Validate entity is not null
if (entity != null)
{
// Answer for question #2

// Make changes on entity
entity.UnitPrice = 49.99m;
entity.Description = "Collector's edition";

/* If the entry is being tracked, then invoking update API is not needed.
The API only needs to be invoked if the entry was not tracked.
https://www.learnentityframeworkcore.com/dbcontext/modifying-data */
// context.Products.Update(entity);

// Save changes in database
context.SaveChanges();
}
}

Entity Framework: Update Records with Include in Net Core 3

This code is prone to errors that will creep up depending on the scenario. When passing entity classes between client and server it is important to understand that the objects passed back to the server are merely serialized copies, not tracked entities. Because of the way serialization works, where a DbContext fetching two Transaction records that both reference a Product with ID: 14 would reference the same entity instance, that same pair of transactions, when deserialized, would have two separate object references, each with a Product ID: 14.

Given your example, at a minimum you would need to do something like:

foreach (var modifyItem in customerTransactionList)
{
var existingItem = _dbContext.CustomerTransactions
.Include(x => x.Product)
.SingleOrDefault(x => x.CustomerTransactionId == modifyItem.CustomerTransactionId );
var trackedProduct = _dbContext.Products.Local(x => x.ProductId == modifyItem.Product.ProductId).SingleOrDefault();
if (trackedProduct != null)
modifyItem.Product = trackedProduct;
else
_dbContext.Products.Attach(modifyItem.Product);

if (existingItem == null)
_dbContext.Add(modifyItem);
else
{
_dbContext.Entry(existingItem).CurrentValues.SetValues(modifyItem);
if(existingItem.Product.ProductId != modifyItem.Product.ProductId)
existingItem.Product = modifyItem.Product; // tracked reference.
}
}
_dbContext.SaveChanges();

}

What this amounts to is checking for an existing transaction like you were doing. However, we also have to check for any cached copies of related entities (Product) that the DbContext may be tracking. If we don't and we try to add a transaction that has a Product with an ID matching one the Context is already tracking we will either get a PK violation or a duplicate Product record with a new Product ID created, depending on how your Product PK is configured. (I.e. DatabaseGenerated.Identity column) We update the Product reference with a local cache instance if one is found, otherwise we tell the DbContext to start tracking the product instance. This assumes that this method cannot accept new products as part of this call, and that the Product record received should legally exist. Handling new products and validating the product passed in would require additional conditional code and DB checks. From there we determine whether the Transaction is an update or an insert. In the case of an Update we can use CurrentValues.SetValues to copy across values, (as above) or Automapper, or manually copy the relevant values across. Assuming it's possible that a transaction could change the product, we also check the Product ID against the modified one, and if it's different we update the Product reference. modifyItem.Product at this point will be pointing to the DbContext tracked reference.

Updating entities with methods like this can be quite involved since you have to account for not only detecting new vs. existing records but potentially updating references to entities that the DbContext is already tracking. My strong recommendation is to adopt view models for explicit Add vs Update operations and deal with operations as atomically as possible. I.e. rather than passing a collection of transactions that might contain updates or inserts to work through, make more granular calls for each singular type of change. (Simpler, faster operations and fewer places for mistakes to occur)

Update a record in Entity Framework Core

Try to use below code:

newDataObjectForSameRow.Id = myId;
MyDataObject myExistingObject = _dbContext.data.Where(s => s.Id == myId).FirstOrDefaultAsync();
_dbContext.Entry(myExistingObject).CurrentValues.SetValues(newDataObjectForSameRow);
_dbContext.SaveChanges();

Update an entire record using entity framework

I think, you can not do this so easily.

You should create a method in your Book class, where you change all of the properties.

result.Update(Book newProperties);
db.SaveChanges();

or

result.Update(string prop1, int prop2, etc.);
db.SaveChanges();

How to update a record using Entity Framework?

Should be something like(I don't know what your classes are called):

using(var context = new SomeEntities())
{
CarrierOperation carrierOperation = context.CarrierOperations.SingleOrDefault(co=> co.id == 14);
if(carrierOperation != null)
{
carrierOperation.last_used = DateTime.Now.AddMinutes(8);
context.SaveChanges();
}
}

How to update a record in database in Entity Framework?

You don't need to add the user again (it already exists and EF tracks changes), simply call SaveChanges and you are done.

Just remove this line:

db.Users.Add(user_to_update);

and it should work (unless there are more errors).

How to Bulk Update records in Entity Framework?

If you don't want to use an SQL statement, you can use the Attach method in order to update an entity without having to load it first :

using (myDbEntities db = new myDbEntities())
{
try
{
//disable detection of changes to improve performance
db.Configuration.AutoDetectChangesEnabled = false;

//for all the entities to update...
MyObjectEntity entityToUpdate = new MyObjectEntity() {Id=123, Quantity=100};
db.MyObjectEntity.Attach(entityToUpdate);

//then perform the update
db.SaveChanges();
}
finally
{
//re-enable detection of changes
db.Configuration.AutoDetectChangesEnabled = true;
}
}


Related Topics



Leave a reply



Submit