如果在DAL中找不到数据,如何在BLL中抛出异常

时间:2012-11-24 11:47:40

标签: asp.net exception-handling data-access-layer bll

当我在文本框中输入的车牌号没有相应的carID时,我试图在我的BLL中抛出异常。

我的DAL看起来像这样:

Public Class DALCar
    Private dc As New cars_modelDataContext

    Public Function getCarIdByLicenePlate(ByVal licensePlate_input As String) As String
        Dim result = (From car In dc.Cars
                    Where car.License_Plate = licensePlate_input
                    Select car.License_Plate).Single
        Return result
    End Function

End Class

这是我的BLL:

Public Class BLLCar
    Private DALcar As New DALCar

    Public Function getCarIdByLicenePlate(ByVal licensePlate_input As String) As String
        Dim carID As String = DALcar.getCarIdByLicensePlate(chassisNo_input)
    End Function

End Class

因此,如果没有使用此特定牌照的carID,我的DAL中会抛出异常,但是如何在我的BLL中而不是在DAL中抛出此异常?

2 个答案:

答案 0 :(得分:0)

因为您在LINQ表达式中使用Enumerable.Single。如果序列中有多个元素或序列为空,则抛出异常。

如果您可以假设序列将始终包含0或1个元素,那么您可以将Single替换为FirstOrDefault(有关详细信息,请参阅后面的内容)。如果序列为空,它将返回序列中的第一个元素或Nothing

在这种情况下,您可以检查BLL中的Nothing并在那里抛出相应的异常。

在你的DAL中这样:

Public Class DALCar
    Private dc As New cars_modelDataContext

    Public Function getCarIdByLicenePlate(ByVal licensePlate_input As String) As String
        Dim result = (From car In dc.Cars
                    Where car.License_Plate = licensePlate_input
                    Select car.License_Plate).FirstOrDefault
        Return result
    End Function
End Class

这在你的BLL中:

Public Class BLLCar
    Private DALcar As New DALCar

    Public Function getCarIdByLicenePlate(ByVal licensePlate_input As String) As String
        Dim carID As String = DALcar.getCarIdByLicensePlate(chassisNo_input)
        If carId = Nothing Then
            Throw New ArgumentException("There is no match.")
        End If
    End Function
End Class

如果您的查询可能返回的元素多于您必须考虑的元素,如果这是一个错误。如果它被允许并且您想要处理(返回)第一个,那么继续FirstOrDefault。如果这是一个错误,那么你应该从你的DAL返回一个枚举并检查你的BLL中的项目数量(否则,使用Single,你仍然会扔进DAL里面。)

答案 1 :(得分:0)

使用FirstOrDefault代替Single

Public Function getCarIdByLicenePlate(ByVal licensePlate_input As String) As String
    Dim result = (From car In dc.Cars
                Where car.License_Plate = licensePlate_input
                Select car.License_Plate).FirstOrDefault 
    Return result


 Public Function getCarIdByLicenePlate(ByVal licensePlate_input As String) As String
    Dim carID As String = DALcar.getCarIdByLicensePlate(chassisNo_input)
    If carID = Nothing Then
       Throw New Exception(String.Format("Can't find car id for chassisNo : {0}", chassisNo_input))
    End If
End Function