2

I'm getting this error:

The model item passed into the dictionary is of type System.Data.Entity.Infrastructure.DbQuery``1[<>f__AnonymousType1``2[System.DateTime,System.Int32]], but this dictionary requires a model item of type System.Collections.Generic.IEnumerable``1[AtAClick.Models.WhatsOn].

This is my controller;

public ViewResult Index(WhatsOn model)
{       
   DateTime myDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

   var datequery =
            db.WhatsOns.Where(c => c.start > myDate).OrderByDescending(c => c.start).GroupBy(c => c.start).Select(
                sGroup => new
                              {
                                  day = sGroup.Key,
                                  whtscount = sGroup.Count()
                              });

   return View(datequery);
}

I want to return all entries after todays date and the number of entries. I'm new to this, any help is greatly apprecieted! Thanks in advance, if you need any mjore detail just let me know. Thanks!

This is my view

==============================

@model IEnumerable<AtAClick.Models.WhatsOn>

@{ ViewBag.Title = "Index"; }

<h2>Index</h2>

<p>@Html.ActionLink("Create New", "Create")</p>
<table>
    <tr>
        <th>start</th>
        <th>end</th>
        <th>Name</th>
        <th>Desc</th>
        <th>link</th>
        <th>CalenderDisplay</th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>@Html.DisplayFor(modelItem => item.day)</td>
        <td>@Html.DisplayFor(modelItem => item.whtscount)</td>          
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}

============================

This is the edit method in my controller;

// // GET: /WhatsOn/Edit/5

    public ActionResult Edit(int id)
    {
        WhatsOn whatson = db.WhatsOns.Find(id);
        return View(whatson);
    }

    //
    // POST: /WhatsOn/Edit/5

    [HttpPost]
    public ActionResult Edit(WhatsOn whatson)
    {
        if (ModelState.IsValid)
        {
            db.Entry(whatson).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(whatson);
    }
Dan
  • 1,450
  • 1
  • 17
  • 34
  • can you edit your post and include the code for your view? – Jon Jul 12 '11 at 11:32
  • Yep, I'll pop it in now... Done. The editor hasd taken out the table tags. It's actually magled it a bit, but the foreach is there. – Dan Jul 12 '11 at 11:37

2 Answers2

0

i think the problem is a mismatch between what your view expects and what your controller is passing.

In your select statement your selecting a new anonymous type but your view is expecting the type IEnumerable<WhatsOn>

assuming the whats on fields are day and whtscount then replace the datequery with

    var datequery =
        db.WhatsOns.Where(c => c.start > myDate).OrderByDescending(c => c.start).GroupBy(c => c.start).Select(
            sGroup => new WhatsOn()
                          {
                              day = sGroup.Key,
                              whtscount = sGroup.Count()
                          });

Update: The error is indicating that your select query cannot be translated into the equivilent sql, what you could try is changing it to

    var datequery =
        db.WhatsOns.Where(c => c.start > myDate).OrderByDescending(c => c.start).GroupBy(c => c.start).AsEnumerable().Select(
            sGroup => new WhatsOn
                          {
                              day = sGroup.Key,
                              whtscount = sGroup.Count()
                          });

Update: I think the issue may be that when you get to the post method of the edit, the WhatsOn object is no longer associated with the database WhatsOn it was originally loaded from, have a go at changing it to

public ActionResult Edit(int id)
{
    WhatsOn whatson = db.WhatsOns.Find(id);
    return View(whatson);
}

[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
    WhatsOn whatsOnmodel = db.WhatsOns.Find(id);

    if (TryUpdateModel(whatsOnmodel))
    {
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(whatsOnmodel );
}

Update: If that approach was not working you could see if your one did just add the loading at the beginning so

[HttpPost]
public ActionResult Edit(int id, WhatsOn whatson)
{
    WhatsOn whatsOnmodel = db.WhatsOns.Find(id);

    if (ModelState.IsValid)
    {
        whatsOnmodel.day = whatson.day;
        whatsOnmodel.whtscount = whatson.whtscount;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(whatsOnmodel);
}

you could test that and see what happens

Update: Actually i think your first approach should of worked but i think it requires the Id, what happens if you make it

[HttpPost]
public ActionResult Edit(int id, WhatsOn whatson)
{
    if (ModelState.IsValid)
    {
        db.Entry(whatson).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(whatson);
}
Manatherin
  • 4,169
  • 5
  • 36
  • 52
  • Thanks for your reply, thst's gotten me a little further, but now I'm getting this error... The entity or complex type 'AtAClick.Models.WhatsOn' cannot be constructed in a LINQ to Entities query. Do I have to edit the foreach in the view to handle this query? Thanks again! – Dan Jul 12 '11 at 11:09
  • This worked without having to use DTO. It's grouping them by date and returniong the count! But, when I try and edit an entry I get this error, feel free to stop helping me by the way, I know it's error after error.. anyway, Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries... Any advice? I'll be marking your answer as correct either way! – Dan Jul 12 '11 at 13:22
  • @Dan would you mind posting the post method of your controller where you are trying to update the records – Manatherin Jul 12 '11 at 13:23
  • It's posted now. Thanks for all this Manatherin! – Dan Jul 12 '11 at 13:26
  • on 'whatsOnmodel.day = whatson.day;' I get 'Server Error in '/' Application. Object reference not set to an instance of an object.'... – Dan Jul 12 '11 at 14:02
  • if I change it to that I get the 'Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.' error. – Dan Jul 12 '11 at 14:04
  • @Dan that sounds like your view is returning a null whatson object, was the model passed into the view null? – Manatherin Jul 12 '11 at 14:09
  • @Dan take a look at http://stackoverflow.com/questions/1836173/entity-framework-store-update-insert-or-delete-statement-affected-an-unexpect this is the same error you are getting it may be the same issue – Manatherin Jul 12 '11 at 14:11
  • Thanks Matherin, you have been a great help! The model passed into the view is not null, there are a number of entries. I have read that question. I'll keep going with it and see how I get on. Thanks again! – Dan Jul 12 '11 at 14:27
0

Your view is expecting an IEnumerable<AtAClick.Models.WhatsOn>, but you are passing a collection of anonymous types. You should change your projection (Select) to instantiate instances of your WhatsOn type instead.

Update

You will need to create a new data transfer object (DTO) type to project onto (e.g. WhatsOnDto), as WhatsOn is an entity type. See The entity cannot be constructed in a LINQ to Entities query for more info. Update your view's model type to an IEnumerable<WhatsOnDto>, or better still a MyViewModel type which contains a property of WhatsOnDtos.

Community
  • 1
  • 1
devdigital
  • 34,151
  • 9
  • 98
  • 120
  • Thanks, I think that's what Manatheirn also suggested. I implemented his soloution but got the error I just posted in a comment below his answer. Any help is appreciated. Thanks! – Dan Jul 12 '11 at 11:12
  • I'll try this now and report back, thanks again, I really appreciate this! 2 mins! – Dan Jul 12 '11 at 11:56
  • I added the class WhatDTO to my WhatsOn.cs model and made the changed you suggested. This worked! But now when I try and edit/update/insert an entry I get the previous error. – Dan Jul 12 '11 at 12:43
  • This is difficult without the code, which error are you getting? – devdigital Jul 12 '11 at 12:54
  • Hi dev, Matherin's updated answer below worked, it's grouping them by date and returning the count. Though when I try and update an entry I get this error (as I said, feel free to get back to whatever you were doing, you've helped me a lot so far!) .... Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.... any advice? – Dan Jul 12 '11 at 13:23