1

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

    <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

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

4

1 回答 1

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

于 2012-12-21T18:15:46.423 回答