在MVC3中如何在数据库中创建项目之前检查重复项?

时间:2012-12-21 18:08:44

标签: database vb.net asp.net-mvc-3 duplicates

在我的控制器“语言”中,我有以下创建操作方法

    <HttpPost()>
    Function Create(language As Language) As ActionResult
        Try
            If ModelState.IsValid Then
                Dim name As String = language.Name
                db.Languages.Add(language)
                db.SaveChanges()
                Return RedirectToAction("Index", New System.Web.Routing.RouteValueDictionary(New With {.languageName = name, .onSuccess = ActionType.CREATE}))
            End If
        Catch ex As DataException
            ViewBag.ErrorTitle = Resources.Commands.UnableToCreate
            ViewBag.ErrorMessage = Resources.Commands.TryAgainMessage
        End Try
        Return View(language)
    End Function

如何在创建之前检查数据库中是否存在具有相同值的重复项?

1 个答案:

答案 0 :(得分:1)

Dim Exists as Boolean = db.Languages.Any(Function (x) x.languageName = language.languageName)
If Not Exists Then
  db.Languages.Add(language)
  db.SaveChanges()
End If

原谅我,我的VB非常生疏

或者在模型中实施IValidatableObject执行检查(可能是更好的方法):

Public Class Language
  Implements IValidatableObject

  ' Model properties

  Public Function Validate(ByVal validationContext As ValidationContext) As IEnumerable(Of ValidationResult) Implements IValidatableObject.Validate
    Dim results As List(Of ValidationResult) = New List(Of ValidationResult)

    '
    ' check if langauge already exists and assign error
    ' to results if necessary
    '

    Return results
  End Function
End Class

关于MVC3模型验证的链接:http://www.devproconnections.com/article/aspnetmvc/modellevel-validation-aspnet-mvc-3-136111