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



我对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 - Index在数组的边界之外不确定LinQ对not表达式做了什么,但肯定不是我想要的。

是否有任何方法来修改数据库字段值时存储到我的自定义对象?

谢谢!

试试这个:

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

相关内容

  • 没有找到相关文章

最新更新