在ASP.NET MVC中,可以使用以下方法防止重复记录的插入:
public class MyEntity
{
// Other properties
[Index("IX_UniqueColumn", IsUnique = true)]
public string UniqueColumn { get; set; }
}
[HttpPost]
public ActionResult Create(MyEntity entity)
{
if (ModelState.IsValid)
{
// Check if the record already exists
if (db.MyEntities.Any(e => e.UniqueColumn == entity.UniqueColumn))
{
ModelState.AddModelError("UniqueColumn", "Record with the same value already exists.");
return View(entity);
}
// Insert the record
db.MyEntities.Add(entity);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(entity);
}
[HttpPost]
public ActionResult Create(MyEntity entity)
{
using (var transaction = db.Database.BeginTransaction())
{
try
{
// Check if the record already exists
if (db.MyEntities.Any(e => e.UniqueColumn == entity.UniqueColumn))
{
ModelState.AddModelError("UniqueColumn", "Record with the same value already exists.");
return View(entity);
}
// Insert the record
db.MyEntities.Add(entity);
db.SaveChanges();
transaction.Commit();
return RedirectToAction("Index");
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
}
以上方法可以防止重复记录的插入。根据具体需求,可以选择适合的方法。