0

我对 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 表达式做了什么,但肯定不是我想要的。

将数据库字段值存储到我的自定义对象中时,有什么方法可以修改它?

谢谢!

4

1 回答 1

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
于 2014-08-18T04:00:11.603 回答