如何使用实体框架核心更新记录? [英] How to update record using entity framework core?
问题描述
在实体框架工作核心中更新数据库表数据的最佳方法是什么?
What is the best approach to update a database table data in entity frame work core ?
- 检索表行,进行更改并保存
- 在数据库上下文中使用关键字更新并处理不存在的项目的异常
- Retrive the table row , do the changes and save
- Use Key word Update in db context and handle exception for item not exist
我们可以在EF6上使用哪些改进的功能?
What are the improved feature we can use over EF6 ?
推荐答案
要使用Entity Framework Core更新实体,这是逻辑过程:
To update an entity with Entity Framework Core, this is the logical process:
- 为
DbContext
类 创建实例 - 通过键检索实体
- 对实体的属性进行更改
- 保存更改
- Create instance for
DbContext
class - Retrieve entity by key
- Make changes on entity's properties
- Save changes
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.
更新方法不会在数据库中保存更改;而是在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
表名称为Product
Table name is Product
产品类别定义:
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();
}
}
请告诉我这是否有用
这篇关于如何使用实体框架核心更新记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!