I have following working Entity Frameowrk code for creating DTO from entity framework result. It created InvoiceDTO object that has a List<ServiceChargeDTO>
property inside it. This is done referring to Mapping Linq Query results to a DTO class
public class InvoiceDTO
{
public int InvoiceID { get; set; }
public List<ServiceChargeDTO> ServiceChargeLineItems { get; set; }
public decimal InvoiceTotal { get; set; }
}
public InvoiceDTO GetInvoiceByID(int invoiceIDParam)
{
InvoiceDTO invoice=null;
using (var db = new PortalEntities())
{
var invoices = from a in db.Invoices
where a.InvoiceID == invoiceIDParam
select new InvoiceDTO
{
InvoiceID = a.InvoiceID,
InvoiceTotal = a.InvoiceAmount,
ServiceChargeLineItems =
(from b in db.InvoiceServiceXrefs
where a.InvoiceID == b.InvoiceID
select new ServiceChargeDTO
{
ServiceChargeID = b.ServiceChargeID,
Quantity = b.ServiceCharge.Qty,
UnitPrice=b.ServiceCharge.UnitPrice,
Amount=b.ServiceCharge.Amount
}
).ToList()
};
invoice = invoices.FirstOrDefault();
}
return invoice;
}
Here data from related tables is successfully retrieved.
InvoiceServiceXrefs.ServiceCharge.Qty
I need to change this approach and make it convert method.
public InvoiceDTO GetInvoiceByID(int invoiceIDParam)
{
var invoice2 = null;
using (var db = new PortalEntities())
{
var invoices2 = from b in db.Invoices
where b.InvoiceID == invoiceIDParam
select b;
invoice2 = ToInvoiceDTO(invoices2.FirstOrDefault());
}
return invoice2;
}
But the navigation properties are not getting listed when I type invoice.InvoiceServiceXrefs.
.
How to get the navigation properties correctly and create InvoiceDTO
object with List<ServiceChargeDTO>
?