LINQ - 如何根据DB将返回的值修改select

时间:2014-08-18 03:22:23

标签: .net vb.net linq lightspeed

我对Linq相对较新,我正在使用.NET开发一个函数,该函数使用linq查询的选定字段实例化POCO

问题是必须在“运行时”转换其中一个字段。

这是我的错误示​​例:

Private Shared Function GetInfectionHistory(HiveId As Long) As IList(Of HiveInfectionDetail)
    Using DB As LandDataModelUnitOfWork = Context.CreateUnitOfWork
            Dim historyResult = From I In DB.HiveAfbInfections
                                Where I.HiveId = HiveId
                                Select New HiveInfectionDetail With {
                                    .DateInfected = I.DateInfected,
                                    .DateCleaned = I.DateCleared,
                                    .PotentialAfbInfection = I.PotentialInfection,
                                    .AfbInfection = Not I.PotentialInfection
                                }
            If IsListEmpty(historyResult.ToList()) Then
                Return Nothing
            End If
            Return historyResult.ToList()
        End Using
End Function

Private Shared Function IsListEmpty(Of T)(source As IEnumerable(Of T)) As Boolean
        If source Is Nothing Then
            Return True
        End If
        Return Not source.Any()
    End Function
enter code here

有问题的一行是我为属性AfbInfection指定一个值。此属性将与数据库中的PotentialInfection相反。因此,如果I.PotentialInfection为True,那么我的属性AfbInfection应为False。如上所述将导致 IndexOutOfRangeException - 索引超出数组的范围不确定LinQ使用NOT表达式做什么,但肯定不是我想要的。

在将数据库字段值存储到自定义对象中时,有没有办法修改数据库字段值?

谢谢!

1 个答案:

答案 0 :(得分:1)

试试这个:

Private Shared Function GetInfectionHistory(HiveId As Long) As IList(Of HiveInfectionDetail)
    Using DB As LandDataModelUnitOfWork = Context.CreateUnitOfWork
            Dim historyQuery1 = From I In DB.HiveAfbInfections
                                Where I.HiveId = HiveId
                                Select New With {
                                    .DateInfected = I.DateInfected,
                                    .DateCleaned = I.DateCleared,
                                    .PotentialInfection = I.PotentialInfection
                                }
            Dim historyQuery2 = From I In historyQuery1.ToArray()
                                Select New HiveInfectionDetail With {
                                    .DateInfected = I.DateInfected,
                                    .DateCleaned = I.DateCleaned,
                                    .PotentialAfbInfection = I.PotentialInfection,
                                    .AfbInfection = Not I.PotentialInfection
                                }
            Dim historyResult = historyQuery2.ToList()
            If IsListEmpty(historyResult) Then
                Return Nothing
            End If
            Return historyResult
        End Using
End Function