我有下面的代码,它使用组来选择不同的值。智能和代码中断显示查询按预期工作。
public ActionResult _PortfoliosbyCountry()
{
var portfolios = db.Portfolios;
var query = (from t in portfolios
group t by new { t.UserId, t.CountryId,t.PortfolioTypeId }
into grp
select new
{
grp.Key.CountryId,
grp.Key.PortfolioTypeId,
grp.Key.UserId
}).ToList();
return PartialView(query);
}
模型
namespace RefST.Models
{
public class Portfolio
{
[Key]
public int PId { get; set; }
[Required]
public string Title { get; set; }
[ScaffoldColumn(false)]
public DateTime DatePosted { get; set; }
[ScaffoldColumn(false)]
public DateTime LastEdited { get; set; }
[AllowHtml][Required]
public string Body { get; set; }
public int UserId {get; set; }
public int CountryId { get; set; }
public int PortfolioTypeId { get; set; }
public virtual Country Country { get; set; }
public virtual PortfolioType PortfolioType { get; set; }
}
}
问题是 razor view 给出了以下错误
传入字典的模型项的类型为:'System.Collections.Generic.List 1[<>f__AnonymousType19
3[System.Int32,System.Int32,System.Int32]]',但此字典需要类型为'System.Collections.Generic.IEnumerable`1[RefST.Models.Portfolio]'的模型项。
@model IEnumerable<RefST.Models.Portfolio>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.UserId)
</th>
<th>
@Html.DisplayNameFor(model => model.CountryId)
</th>
<th>
@Html.DisplayNameFor(model => model.PortfolioTypeId)
</th>
<th></th>
</tr>
@foreach (var b in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => b.UserId)
</td>
<td>
@Html.DisplayFor(modelItem => b.CountryId)
</td>
<td>
@Html.DisplayFor(modelItem => b.PortfolioTypeId)
</td>
</tr>
}
</table>
如果有人能指出正确的方向,我将不胜感激
最佳答案
我认为在这一行中你可以这样做:
select new PortFolio
{
countryId= grp.Key.CountryId,
PortfolioTypeId= grp.Key.PortfolioTypeId,
UserId= grp.Key.UserId,
//Add others members with default value
Titel=string.Empty;
....
}).ToList();
所以你确定你发送了一个IEnumerable<Portfolio>
作为 Model
关于c# - Linq GroupBy 匿名类型错误 MVC4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23181953/