如何使用实体框架核心更新记录?
问题描述:
在实体框架工作核心中更新数据库表数据的最佳方法是什么?如何使用实体框架核心更新记录?
- Retrive表行,做的修改并保存
- 使用关键字更新在数据库方面,以及处理项目的异常不存在
哪些改进的功能,我们就可以使用了EF6?
答
我将假设一些对象定义来回答你的问题:数据库名称是Store,并且有一个名为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类的定义:
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 product = 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";
// Update entity in DbSet
context.Products.Update(entity);
// Save changes in database
context.SaveChanges();
}
}
请让我知道这是非常有用的
谢谢你。这是如何使用 的一个很好的例子2.在数据库上下文中使用关键字更新并处理不存在的项的异常。 我更感兴趣的是选择哪一个作为最佳实践。 – Charith