2012-12-21 50 views
1

在我的控制器「語言」我有以下的創建操作方法在MVC3中如何在數據庫中創建項目之前檢查重複項?

<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
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

相關問題