Pixelstiltskin
Pixelstiltskin

Reputation: 332

Linq to Object referencing a list

I have two disparate datasources, one has details about Clients the other the Site that only has a ClientID but due to partial migration of a system I can't join them at a database level (yet, that will eventually happen!):

  var clients = _clientService.GetClientSummary(true);
  var results = context.Sites.AsNoTracking().OrderByDescending(s => s.Id).
                Skip((pageIndex - 1) * pageSize).Take(pageSize);

            result.Content = pageResult.Select(a => new QuoteSearch
            {
                Accepted = a.Accepted,
                Created = a.Created,
                Id = a.Id,
                Customer = clients.Find(b => b.Id == a.ClientId).Name
            }).ToList();

Running the code above returns an error

"LINQ to Entities does not recognize the method 'CertsAssured.Model.Client.ClientSummary Find(System.Predicate`1[CertsAssured.Model.Client.ClientSummary])' "

I can write the code after this step to perform the task but would then have to save the ClientId in to my object to then iterate through. Is there a way of getting the info from the client list during the Select method?

Thanks

Upvotes: 1

Views: 37

Answers (1)

Joachim Isaksson
Joachim Isaksson

Reputation: 181077

After the database filtering/paging is set up, you can use AsEnumerable to convert the IQueryable result to an in memory IEnumerable where you can do lookups against clients;

result.Content = pageResult
        .AsEnumerable()
        .Select(a => new QuoteSearch
        {
            Accepted = a.Accepted,
            Created = a.Created,
            Id = a.Id,
            Customer = clients.Find(b => b.Id == a.ClientId).Name
        }).ToList();

If there are many database fields and you don't want all of the fetched from the database, you can filter the fields on the IQueryable first, something like;

result.Content = pageResult
        .Select(a => new                    // This filters in the database
        {                                   // to an anonymous type
            Accepted = a.Accepted,
            Created = a.Created,
            Id = a.Id,
            ClientId = a.ClientId
        })
        .AsEnumerable()                     // Convert to an IEnumerable 
        .Select(a => new QuoteSearch        // This is done in-memory
        {                                   // generating the real type
            Accepted = a.Accepted,
            Created = a.Created,
            Id = a.Id,
            Customer = clients.Find(b => b.Id == a.ClientId).Name
        }).ToList();

Upvotes: 1

Related Questions