在实体框架工作核心中更新数据库表数据的最佳方法是什么?
我们可以在EF6上使用哪些改进的功能?
要使用Entity Framework Core更新实体,这是逻辑过程:
DbContext
类的实例Update()
方法DbContext
:
开始以“已修改”状态跟踪给定实体,以便在
SaveChanges()
调用该实体时在数据库中对其进行更新。
更新方法不会将更改保存在数据库中;相反,它为DbContext实例中的条目设置状态。
因此,我们可以在调用Update()
方法之前将更改保存到数据库中。
我将假设一些对象定义来回答您的问题:
数据库名称为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类的定义:
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] 删除。
我来说两句