如何使用实体框架核心更新记录?

查理斯:

在实体框架工作核心中更新数据库表数据的最佳方法是什么?

  1. 检索表行,进行更改并保存
  2. 在数据库上下文中使用关键字更新并处理项目不存在的异常

我们可以在EF6上使用哪些改进的功能?

赫兹(H. Herzl):

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

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

Update()方法DbContext

开始以“已修改”状态跟踪给定实体,以便在SaveChanges()调用该实体时在数据库中对其进行更新

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

因此,我们可以在调用Update()方法之前将更改保存到数据库中。

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

  1. 数据库名称为Store

  2. 表名称为产品

产品类别定义:

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

    public string ProductName { get; set; }

    public string Description { get; set; }

    public decimal? UnitPrice { get; set; }
}

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

更新实体的逻辑:

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

请告诉我这是否有用

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章