使用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来处理验证结果。当用户提交表单时,如果模型未通过验证,将显示相应的错误信息。