c# - Linq 在 ASP.NET MVC 控制器的 ViewModel 中生成 IEnumerable
问题描述
我正在尝试将我的 linq 查询结果放入视图模型中,但我不断收到错误消息。Linq 查询返回多个评分结果。我想将这些多重评分结果放在一个 IEnumerable 中。
错误:无法将类型 Models.CustomerRating' 隐式转换为 'System.Collections.Generic.IEnumerable<Models.CustomerRating>'。存在显式转换(您是否缺少演员表?)
LINQ查询
var data = from profile in _context.Customers
join rating in _context.CustomerRating
on profile.strUserID equals rating.strUserID into rt
from subrating in rt.DefaultIfEmpty()
where profile.strUserID == UserId
select new { p = profile, r = subrating };
我的视图模型:
public class ServiceProvider
{
public CustomerProfile Customer { get; set; }
public IEnumerable<CustomerProfile> CustomerProfiles { get; set; }
public CustomerServices CustomerServices { get; set; }
public FilterServicesViewModel FilterServices { get; set; }
public CustomerRating Rating { get; set; }
public IEnumerable<CustomerRating> CustomerRating { get; set; }
}
我想将配置文件的结果添加到 Customer 并细分到 CustomerRating IEnumerable
。
我尝试了以下方法,但出现错误:
foreach (var v in data)
{
serviceProviderViewModel.Customer = v.p;
serviceProviderViewModel.CustomerRating = v.r;
}
解决方案
创建一个新列表并遍历您的 linq 查询结果并将其添加到该列表中
List<CustomerRating> RatingList = new List<CustomerRating>();
foreach (var v in data)
{
serviceProviderViewModel.Customer = v.p;
RatingList.Add(v.r);
}
serviceProviderViewModel.CustomerRating = RatingList;
推荐阅读
- javascript - 避免在 React 中由对象字面量引起的重新渲染:如何处理对象中的变量?
- php - CakePHP 3 - 分隔 JOIN 条件时使用不同的表别名
- jquery - 三消比赛
- google-chrome - 如何在 Chromebook 上使用 Assembla SVN 更新和提交?
- html - 更改 div 与背景图像之间的弹性间距
- c# - 来自 Azure 的 .net 核心流文件并调整大小
- bash - Bash PS1 提示设置 \h 在第一个点之后去除主机名
- google-bigquery - 在标准 SQL / BigQuery 中将 YYYYMMDD 字符串转换为日期
- java - 匿名内部类中不允许使用 Java continue 语句
- javascript - Bokeh & Custom JS - 使用滑块更新多线图