Search code examples
c#asp.net-mvclinqiqueryable

MVC4 linq query to object doesn't come out as the correct object


Error: The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery (snip) ...looking for type 'Advocate'

Controller method looks like this:

[HttpGet]
public ActionResult AdvocateEdit(int id)
{
    var advocate = from a in db.Query<Advocate>().Include(a => a.AdvocateId)
                   where (a.AdvocateId == id)
                   select a;

    return View(advocate);
}

The view is indeed typed to the Advocate @model and after stepping through, I'm pretty sure the problem is this query. It needs to be of type Advocate when it returns.

db.Query is an IQueryable<T> method in my DbContext that returns Set<T>().

Let me know if more info is needed. Thanks people

ADDED ----

DbContext.cs

public interface IAcmeDb : IDisposable
{
    IQueryable<T> Query<T>() where T : class;
}

public class AcmeDb : DbContext, IAcmeDb
{
    public AcmeDb() : base("name=AcmeDB") {}
    public DbSet<Advocate> Advocates { get; set; }

    IQueryable<T> IAcmeDb.Query<T>()
    {
         return Set<T>();
    }
}

Solution

  • If your view requires a single Advocate and there is always only one entity for a given id then you want:

    [HttpGet]
    public ActionResult AdvocateEdit(int id)
    {
       try
       {
           Advocate advocate = db.Query<Advocate>().Single(a => a.AdvocateId == id);
           return View(advocate);
       }
       catch(InvalidOperationException ex)
       {
          //handle the case where no entity matches the supplied id (return status code 404?), or
          //there are no Advocates at all (redirect to a create page?), or
          //more than one entity matches (return status code 500)
       }
    }