如何使用 Entity Framework Core 更新记录?
在 Entity Framework Core 中更新数据库表数据的最佳方法是什么?
What is the best approach to update database table data in Entity Framework Core?
- 检索表格行,进行更改并保存
- 在数据库上下文中使用关键字更新并处理项目不存在的异常
- Retrieve the table row, do the changes and save
- 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:
- 为
DbContext
类创建实例 - 通过键检索实体
- 更改实体的属性
- 保存更改
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:
数据库名为 Store
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();
}
}