简体   繁体   English

在 ASP.NET MVC 控制器中的 ViewModel 中,Linq 结果为 IEnumerable

[英]Linq Results into IEnumerable in ViewModel in ASP.NET MVC Controller

I am trying to put my linq query results into view model but I keep getting an error.我试图将我的 linq 查询结果放入视图模型中,但我一直收到错误消息。 Linq query returns multiple rating results. Linq 查询返回多个评分结果。 I would like to put these multiple rating results in an IEnumerable.我想将这些多重评级结果放在一个 IEnumerable 中。

Error: Cannot implicitly convert type Models.CustomerRating' to 'System.Collections.Generic.IEnumerable<Models.CustomerRating>'.错误:无法将 Models.CustomerRating 类型隐式转换为 'System.Collections.Generic.IEnumerable<Models.CustomerRating>'。 An explicit conversion exists (are you missing a cast?)存在显式转换(您是否缺少演员表?)

Linq query 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 };

My view model:我的视图模型:

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; }
}

I would like to the results of profile to be added to Customer and subrating to CustomerRating IEnumerable .我想将配置文件的结果添加到 Customer 并将子评级到 CustomerRating IEnumerable

I have tried the following but I get an error:我尝试了以下操作,但出现错误:

foreach (var v in data)
{
    serviceProviderViewModel.Customer = v.p;
    serviceProviderViewModel.CustomerRating = v.r;
}

Create a new list and loop through your linq query results and add it to that list创建一个新列表并遍历 linq 查询结果并将其添加到该列表中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM