2
在實體框架工作核心中更新數據庫表數據的最佳方法是什麼?如何使用實體框架核心更新記錄?
- Retrive錶行,做的修改並保存
- 使用關鍵字更新在數據庫方面,以及處理項目的異常不存在
哪些改進的功能,我們就可以使用了EF6?
在實體框架工作核心中更新數據庫表數據的最佳方法是什麼?如何使用實體框架核心更新記錄?
哪些改進的功能,我們就可以使用了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