3

Error:

{"'object' does not contain a definition for 'Id'."}

ViewModel

public class PilotoVM
{
    private FormulaEntities1 db = new FormulaEntities1();

    public IQueryable<object> calcularValoracion()
    {
        return db.Piloto.GroupBy(p => p.id).Select(p => new { Id = p.Key, Valoracion = p.Sum( i=> i.agresividad + i.paciencia + i.reflejos + i.valentia + i.valentia)});
    }
}

Controller

public ActionResult Index()
{
    ViewBag.valoracion = pilotoVM.calcularValoracion();
    return View(piloto.ToPagedList(pageNumber, pageSize));
}

View

@foreach (var pil in ViewBag.valoracion)
{
    <p>@pil.Id</p>
    <p>@pil.Valoracion</p>
}

Error in pil.Id

ragerory
  • 1,360
  • 1
  • 8
  • 27
  • 1
    You're returning an anonymous type list to `IQueryable`. That's just begging for trouble. You should be resolving to a collection of strongly typed objects. – David L Jun 04 '15 at 18:52
  • It's not a good Idea return IQueryable to your controller, it's better to return a model http://stackoverflow.com/questions/2215057/asp-mvc-should-services-return-iqueryables – Marc Cals Jun 04 '15 at 18:54

2 Answers2

0

You should either create a strongly typed object representing your Id and Valoracian, or you could use a Tuple.

public List<Tuple<int, int>> calcularValoracion()
{
    return db.Piloto
        .GroupBy(p => p.id)
        .Select(p => new Tuple<int, int>(
            p.Key, 
            p.Sum(i => i.agresividad + i.paciencia + i.reflejos + i.valentia + i.valentia))
        .ToList();
}

View

@foreach (var pil in ViewBag.valoracion)
{
    @pil.Item1
    @pil.Item2
}

Note the .ToList() at the end of the query. This resolve your query to an in memory collection so that you won't leak your context into your view.

Finally, method names in C# should be Pascal Cased, such as CalcularValoracion().

David L
  • 32,885
  • 8
  • 62
  • 93
0

Your method calcularValoracion() returns an anonymous object. Anonymous types are internal and cant be accessed in the view (refer this article for a good explanation).

Instead, create a view model to represent you data

public class PilotoVM
{
  public int Id { get; set; }
  public int Valoracion { get; set; }
}

then in the controller

List<PilotoVM> model = db.Piloto.GroupBy(p => p.id).Select(p => new PilotoVM()
{
  Id = p.Key, 
  Valoracion = p.Sum( i=> i.agresividad + i.paciencia + i.reflejos + i.valentia + i.valentia)
}).ToList();

Now you can return a strongly typed model to your view and access the propertues of each PilotoVM object in a loop.