C#dynamic throws RuntimeBinderException(' object'不包含xxx的定义)

时间:2014-06-25 14:56:41

标签: c# linq razor

我有以下LINQ语句:

var genre = model.ModelGenres.Where(q => q.Active);
var genreWithFeedbackAverage = genre
                .Select(q => new { Genre = q, Average = (q.ModelRate.Interaction + q.ModelRate.Attitude + q.ModelRate.Posing) / 3 })
                .GroupBy(q => q.Genre)
                .Select(q => new { Genre = q.Key, Average = (int)Math.Round(q.Average(p => p.Average)) });
var debugList = genreWithFeedbackAverage.ToList();
this.ViewBag.GenreAverage = genreWithFeedbackAverage.ToList();

在Razor视图中,我访问了GenreAverage

var genres = this.ViewBag.GenreAverage;

@foreach (var genre in genres)
{
    <tr>
        <td>
            @genre.Genre.Tag.Name
        </td>
        <td>
            @genre.Average
        </td>
    </tr>
}

但是,在第4行,genre.Genre引发以下异常:

  

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:'object'可以   不包含'Genre'的定义

我尝试调试但无法找到此异常的原因,因为该对象显然有它:

enter image description here

如何解决此问题?我是否必须创建一个具体的类,并停止使用anonnymous类?

P.s:我试图注释掉那一行,正如预期的那样,Average也不是一个有效的定义。

解答: 问题与此主题类似(您无法在ViewBag中传递anonnymous类型):Stuffing an anonymous type in ViewBag causing model binder issues

我必须创建一个具体的类:

public class GenreWithAverageViewModel
{

    public ModelGenre Genre { get; set; }
    public int Average { get; set; }

}

并更改LINQ语句:

        var genreWithFeedbackAverage = genre
            .Select(q => new { Genre = q, Average = (q.ModelRate.Interaction + q.ModelRate.Attitude + q.ModelRate.Posing) / 3 })
            .GroupBy(q => q.Genre)
            .Select(q => new GenreWithAverageViewModel { Genre = q.Key, Average = (int)Math.Round(q.Average(p => p.Average)) });

0 个答案:

没有答案