0

私はLinqに比較的慣れておらず、linqクエリの選択されたフィールドでPOCOをインスタンス化する関数を.NETで開発しています。

問題は、これらのフィールドの 1 つを「実行時に」変換する必要があることです。

これは私の誤動作の例です:

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 式で何をしているのかわかりませんが、確かにそれは私が望むものではありません。

カスタム オブジェクトに格納するときに DB フィールドの値を変更する方法はありますか?

ありがとうございました!

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 に答える