使用Entity Framework進行數據驗證,可以遵循以下步驟:
以下是一個示例代碼,演示如何使用Entity Framework進行數據驗證:
public class Product
{
[Required(ErrorMessage = "Product name is required.")]
[StringLength(100, ErrorMessage = "Product name must be less than 100 characters.")]
public string Name { get; set; }
[Required(ErrorMessage = "Price is required.")]
[Range(0.01, 10000, ErrorMessage = "Price must be between 0.01 and 10000.")]
public decimal Price { get; set; }
}
public class MyDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// 其他模型配置代碼
}
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
// 處理并發更新沖突
throw;
}
}
}
public class ProductsController : Controller
{
private readonly MyDbContext _context;
public ProductsController(MyDbContext context)
{
_context = context;
}
[HttpPost]
public ActionResult Create(Product product)
{
if (ModelState.IsValid)
{
_context.Products.Add(product);
_context.SaveChanges();
return RedirectToAction("Index");
}
// 如果模型狀態無效,則返回視圖并顯示錯誤信息
return View(product);
}
}
在上面的示例中,我們在Product實體類中定義了三個驗證屬性,并在ProductsController控制器中使用ModelState來處理驗證結果。當用戶提交表單時,如果模型未通過驗證,將顯示相應的錯誤信息。