How to update record using entity framework core?

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

Question

What is the best approach to update a database table data in entity frame work core ?

  1. Retrive the table row , do the changes and save
  2. Use Key word Update in db context and handle exception for item not exist

What are the improved feature we can use over EF6 ?

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

Popular Answer

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

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

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

Please let me know if this is useful

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