错误:传递到字典中的模型项的类型为'System.Data.Entity.Infrastructure.DbQuery(snip)...正在寻找类型'Advocate'

控制器方法如下所示:

[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);
}


该视图确实输入到Advocate @model,并且逐步执行之后,我确定问题出在此查询上。返回时,其类型必须为Advocate。

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


让我知道是否需要更多信息。谢谢大家

添加 - -

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>();
    }
}

最佳答案

如果您的视图只需要一个Advocate并且给定id始终只有一个实体,那么您需要:

[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)
   }
}

10-07 12:04