I have the following Data Transfer Objects defined:
Public Class MemberWithAddressesDTO
Public Property Member_PK As Integer
Public Property Firstname As String
Public Property DefaultAddress As AddressDTO
Public Property Addresses As IQueryable(Of AddressDTO)
End Class
Public Class AddressDTO
Public Property Address_PK As Integer
Public Property Address1 As String
Public Property Address2 As String
End Class
I have defined the following expression which maps my entity to my DTO so that I can reuse this in queries (the actual expression is generated by T4 template):
Public Shared AsAddressDTO As Expression(Of Func(Of Address, AddressDTO)) =
Function(ent As Address) New AddressDTO With {.Address_PK = ent.Address_PK, _
.Address1 = ent.Address1,
.Address2 = ent.Address2}
I can use this expression in a LINQ-to-Entities query to convert lists of Address entities to list of AddressDTOs:
Using context As New DbContext
Dim mem As MemberWithAddressesDTO =
context.Members _
.Where(Function(m) m.Person_PK = 121) _
.Select(Function(m) New MemberWithAddressesDTO With {
.Member_PK = m.Person_PK, _
.Firstname = m.Firstname, _
.Addresses = ent.Addresses.AsQueryable.Select(AsAddressDTO)}
).FirstOrDefault()
End Using
This works fine, however if I want to use the same expression to convert a single field in member to an AddressDTO in the anonymous type, the only way I can get this to work is to put the field in a single item array, cast to queryable and then call select on that - this seems a bit circuitous and I am wondering if there is a better way:
Using context As New DbContext
Dim mem As MemberWithAddressesDTO = _
context.Members _
.Where(Function(m) m.Person_PK = 121) _
.Select(Function(m) New MemberWithAddressesDTO With {
.Member_PK = m.Person_PK, _
.Firstname = m.Firstname, _
.DefaultAddress = {m.DefaultAddress}.AsQueryable.Select(AsAddressDTO).FirstOrDefault}
).FirstOrDefault()
End Using
Basically I want to know if there is better syntax to achieve this line in the above:
.DefaultAddress = {m.DefaultAddress}.AsQueryable.Select(AsAddressDTO).FirstOrDefault}
Note m.DefaultAddress is a single field of type Address - it is not a collection.
Any ideas?