如何从可枚举转换为特定模型

How to cast from enumerable to a specific model

EF 6 Net Core:我从一个包含 55 个不同类型字段的模型(class 客户)创建了一个 table,但是当我查询相关的 table 我只很少需要这些字段 所以我最终得到一个可枚举的列表,我需要将其转换回客户模型(出于其他原因)

我只知道如何使用 foreach 循环来做到这一点,但它有很多代码。

我尝试使用下面的这些示例进行转换,但转换给出了一个异常并且 OfType 总是返回 count = 0;

所以我使用 for 循环解决方案,但有时需要编写很多代码,因为某些 table 需要比其他字段更多的字段。 能不能投?

// 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 
       ........

    }))
}

直接创建仅包含您需要的值的 Customer 列表。

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

在那种情况下,就不需要您的变量 list1result.

中直接有你想要的