[英]Linq GroupBy anonymous type error MVC4
我下面的代码使用group选择不同的值。 智能和代码中断显示查询正在按预期方式工作。
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; }
}
}
问题是出现以下错误的剃刀视图。传递到字典中的模型项的类型为: '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
如果您删除了过多的.NET通用语法,则错误消息非常清楚出了什么问题:
The model item passed into the dictionary is of type: 'List<AnonymousType<int, int, int>>', but this dictionary requires a model item of type 'IEnumerable<Portfolio>'.
在您的代码中,如果忽略分组,则实际上是在这样做:
from x in y ...
select new { CountryId = x.a, PortfolioTypeId = x.b, UserId = x.c }
这将产生一个匿名类型,该类型恰好具有三个整数字段。 尽管您没有给该类型命名,但编译器已为其命名,这是您永远不能在C#中为您自己的类型使用的名称(在这种情况下,它称为<>f__AnonymousType19
)。
当两个匿名类型具有相同顺序的相同类型的相同字段时,编译器会将它们视为相同类型。 但是,匿名类型永远不会与您自己命名的类型相同,并且编译器不会自动在它们之间进行转换。 您的Razor视图需要一个Portfolio
类型的对象的列表,并且向您发送的不是该对象的列表。 匿名类型恰好具有正确的三个字段这一事实与编译器无关-它只是错误的类型 。
幸运的是,这很容易解决。 在LINQ查询中选择正确的命名类型:
from x in y ...
select new Portfolio { CountryId = x.a, PortfolioTypeId = x.b, UserId = x.c }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.