Home > Blockchain >  How to cast from enumerable to a specific model
How to cast from enumerable to a specific model

Time:11-18

EF 6 Net Core: I created a table from a model (class Customer) that contains 55 fields of different types, but when I query the related table I only need few of those fields so I end up with an enumerable list, that I need to convert back to Customer model (for other reasons)

I only know how to do that using the foreach loop but it is a lot of code.

I tried to convert using these examples below but the cast gives an exception and the OfType always retunr count = 0;

So I use the for loop solution, but sometimes it is a lot of code to write because some tables require more fields than others. Is it possible to cast or not ?

// This is the (var) result from the query. It has a count of 758  
var result = (from r in _context.Customers
              select new
               {
                 r.IdNo,
                 r.Status,
                 r.RenterName,
               }).ToList();

// This always return count = 0
List<Customer> list1 = result.OfType<Customer>().ToList();

// This crash with exception message "Unable to cast object of type...."
List<Customer> list1 = result.Cast<Customer>().ToList();

// That is my possible solution
foreach (var item in result)
{
    list1.Add(new Customer() {

       // Add all required fields here 
       ........

    }))
}

CodePudding user response:

Create directly a List of Customer with only your needed values.

var result = context.Customers
    .Select(c => new Customer
    {
      c.IdNo,
      c.Status,
      c.RenterName,
    })
    .ToList();

In that case, there is no need for your variable list1. You directly have what you want in result.

  • Related