首页 > 解决方案 > 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;
}

标签: c#asp.net-mvclinq

解决方案


创建一个新列表并遍历您的 linq 查询结果并将其添加到该列表中

    List<CustomerRating> RatingList = new List<CustomerRating>();
            foreach (var v in data)
            {
                serviceProviderViewModel.Customer = v.p;
                RatingList.Add(v.r); 
            }
            serviceProviderViewModel.CustomerRating = RatingList;

推荐阅读