【问题标题】:How to cast from enumerable to a specific model如何从可枚举转换为特定模型
【发布时间】:2021-12-25 17:47:46
【问题描述】:

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

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

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

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

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

    }))
}

【问题讨论】:

  • 你能用 Linq 调用 .Select 并在该操作中显式转换吗?
  • 您可以select new 作为客户吗?所以以后你不需要投射任何东西。

标签: c# entity-framework


【解决方案1】:

直接创建一个 Customer 列表,其中仅包含您需要的值。

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

在这种情况下,不需要您的变量list1。你直接在result有你想要的。

【讨论】:

    猜你喜欢
    • 2010-10-11
    • 1970-01-01
    • 2012-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多