如何使用 Entity Framework Core 更新记录? [英] How to update record using Entity Framework Core?

查看:35
本文介绍了如何使用 Entity Framework Core 更新记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Entity Framework Core 中更新数据库表数据的最佳方法是什么?

What is the best approach to update database table data in Entity Framework Core?

  1. 检索表格行,进行更改并保存
  2. 在数据库上下文中使用关键字更新并处理项目不存在的异常
  1. Retrieve the table row, do the changes and save
  2. Use keyword Update in DB context and handle exception for item not exist

相比 EF6,我们可以使用哪些改进功能?

What are the improved features we can use over EF6?

推荐答案

要使用 Entity Framework Core 更新实体,这是逻辑过程:

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

  1. DbContext 类创建实例
  2. 通过键检索实体
  3. 更改实体的属性
  4. 保存更改

DbContext 中的

Update() 方法:

开始跟踪处于修改状态的给定实体,以便在调用 SaveChanges() 时在数据库中更新它.

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

Update 方法不会保存数据库中的更改;相反,它为 DbContext 实例中的条目设置状态.

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

因此,我们可以先调用 Update() 方法来保存数据库中的更改.

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

我将假设一些对象定义来回答您的问题:

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

  1. 数据库名为 Store

  1. Database name is Store

表名是产品

产品类别定义:

public class Product
{
    public int? ProductID { get; set; }
    
    public string ProductName { get; set; }
    
    public string Description { get; set; }
    
    public decimal? UnitPrice { get; set; }
}

DbContext 类定义:

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

更新实体的逻辑:

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 Core 更新记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆