How to update record using entity framework core?

.net-core entity-framework-6 entity-framework-core

Question

How should a database table's data be updated in the entity framework core?

  1. to make changes, get the table row, and then save
  2. Use the key phrase Update in the database context and handle the exception for the missing item.

What have been the improvements over EF6 that we can use?

1
54
10/10/2017 2:32:00 AM

Popular Answer

The logical procedure for updating an object using Entity Framework Core is as follows:

  1. Make an instance ofDbContext class
  2. Retrieve entity by key
  3. alter the entity's attributes.
  4. Save changes

Update() approach inDbContext :

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

Instead of saving changes to the database, the update method sets states for items in the DbContext instance.

Therefore, we may useUpdate() technique used before saving database updates.

To respond to your query, I'll make the following assumptions about object definitions:

  1. database is called Store.

  2. Name of table is Product.

Definition of a product class:

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

    public string ProductName { get; set; }

    public string Description { get; set; }

    public decimal? UnitPrice { get; set; }
}

Definition of class DbContext:

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);
    }
}

Update entity logic:

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";

            // Update entity in DbSet
            context.Products.Update(entity);

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

Let me know if this is helpful if possible.

69
6/4/2019 8:15:19 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow