Home > Blockchain >  Convert list object to IEnumerable<> in ASP.NET Core
Convert list object to IEnumerable<> in ASP.NET Core

Time:05-29

I built a join query using EF in the controller side.

How can I pass the columns that I need from the controller to the view?

My query is :

var unretObj = _unitOfWork.CartsTransaction.GetUnreturnedCarts(branchId, compId)
                          .Join(_unitOfWork.ApplicationUser.GetAll(),
                                ct => ct.UserId,
                                au => au.UserId,
                                (ct, au) => new { ct, au })
                          .Join(_unitOfWork.Lock.GetAll(),
                                ctau => ctau.ct.CartMacId,
                                l => l.MacId,
                                (ctau, l) => new { ctau,l })
                          .Select(result => new
                                            {
                                                result.ctau.ct.UnlockTime,
                                                result.l.LockIdByComp,
                                                result.ctau.au.FullName,
                                                result.ctau.au.PhoneNumber
                                            }).ToList();

I created a model class (not mapped to the database) with the columns that I need:

[NotMapped]
public class UnreturnedLocks 
{
        public DateTime UnlockTime { get; set; }
        public int LockNumber { get; set; }
        public string FullName { get; set; }
        public string PhoneNumber { get; set; }
}

How can I convert the object unretObj to an IEnumerable<UnreturnedLocks> so that I can pass it to the view ?

Or is there another way to use the general object in the view without converting it?

CodePudding user response:

.Select(result => new {...} will return an IQueriable of anonymous objects, you then need to convert them to IEnumerable<UnreturnedLocks> like this:

...
.Select(result => new
{
    result.ctau.ct.UnlockTime,
    result.l.LockIdByComp,
    result.ctau.au.FullName,
    result.ctau.au.PhoneNumber
})
.AsEnumerable()
.Select(res => new UnreturnedLocks
{
   UnlockTime = res.UnlockTime
   ....
})
.ToList();

Alternatively, you can use Automapper Queryable Extensions

  • Related