Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all articles
Browse latest Browse all 1698

One-to-many projection in a Web API NET5.0 controller - how to do it?

$
0
0

I set out to create a controller to retrieve Transaction properties for display purposes later on.

A single Txn has all the typical properties you would expect such as a TDate, IsPaid, the initials of the ServiceProvider and a Charge.

The charge is the total of the services provided, each Txn will have multiple Services each with their own rate (the 1-to-many).

My model looks like this

public class RecordDetail
    {
        public int TransactionId { get; set; }
        public string TDate { get; set; }
        public string BDate { get; set; }
        public string Initials { get; set; }
        public bool IsBilled { get; set; }
        public bool IsPaid { get; set; }
        public string SvcLevel { get; set; }

        public List<Service> Services { get; set; }

    }

and the controller:

[Route("DetailByClient/{pId}/{cId}")]
        [HttpGet]
        public async Task<ActionResult<List<RecordDetail>>> GetRecordDetailsByProvider(int pId, int cId) => await context.Transactions
            .Where(t => t.ProviderId == pId && t.ClientId == cId)
            .Select(t => new RecordDetail
            {
                TransactionId = t.TransactionId,
                TDate = t.Tdate != null ? t.Tdate.ToString() : "n/a",
                BDate = t.Bdate != null ? t.Bdate.ToString() : "n/a",
                Initials = t.Provider.User.Initials,
                IsPaid = t.IsPaid.HasValue ? (bool)t.IsPaid == true : (bool)t.IsPaid == false,
                SvcLevel = t.ProviderSvcTransactions.FirstOrDefault().ProviderService.ServiceLevel.SvcLevel,
                Services = (List<Service>)t.ProviderSvcTransactions
            })
            .ToListAsync();

This gives me the following error:

Unable to cast object of type 'System.Collections.Generic.HashSet`1[BtApiEf5.Model.ProviderSvcTransaction]' to type 'System.Collections.Generic.List`1[BtApiEf5.Model.Service]'.

I understand what it is complaining about, but I do not know how to fix it, or if I have made the right decision to do this in a single action.

Would appreciate your thoughts on how to proceed from here.

TIA


Viewing all articles
Browse latest Browse all 1698

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>