Reputation: 11
When I change query I got an error. Could you please help?
public ActionResult Index(int? id)
{
Models.MyProjectEntities entity = new Models.MyProjectEntities();
// NORMAL QUERY, NO PROBLEM
//var Messages = entity.Message.Where(x => x.Active);
// JOINED QUERY, GENERATES ERROR
var Messages = entity.Message.Join(entity.Categories,
m => m.CategoriID,
k => k.CategoriID,
(m, k) => new { Message = m, Categories = k })
.Where(x => x.Message.Active);
return View(Messages);
}
Here is aspx file first line
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MyProject.Models.Message>>" %>
Here is the Error
The model item passed into the dictionary is of type 'System.Data.Objects.ObjectQuery`1[<>f__AnonymousType7`2[MyProject.Models.Message,MyProject.Models.Categories]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[MyProject.Models.Message]'.
Upvotes: 1
Views: 449
Reputation: 4914
public ActionResult Index(int? id)
{
Models.MyProjectEntities entity = new Models.MyProjectEntities();
// NORMAL QUERY, NO PROBLEM
//var Messages = entity.Message.Where(x => x.Active);
// JOINED QUERY, GENERATES ERROR
var Messages = entity.Message.Join(entity.Categories,
m => m.CategoriID,
k => k.CategoriID,
(m, k) => new { Message = m, Categories = k })
.Where(x => x.Message.Active)
.Select(x => x.Message);
return View(Messages);
}
or if you need categories as well, you should change views model type
EDIT:
public ActionResult Index(int? id)
{
Models.MyProjectEntities entity = new Models.MyProjectEntities();
// NORMAL QUERY, NO PROBLEM
//var Messages = entity.Message.Where(x => x.Active);
// JOINED QUERY, GENERATES ERROR
var Messages = entity.Message.Join(entity.Categories,
m => m.CategoriID,
k => k.CategoriID,
(m, k) => new MessageWithCategories { Message = m, Categories = k })
.Where(x => x.Message.Active);
return View(Messages);
}
and model type should be MessageWithCategories (this class has to be created)
Upvotes: 0
Reputation: 2429
Because your joining an your creating an anonymous type, you need to do
var Messages = entity.Message.Join(entity.Categories,
m => m.CategoriID,
k => k.CategoriID,
(m, k) => new { Message = m, Categories = k })
.Where(x => x.Message.Active)
.Select(x => new Message { ... .. .. } );
Upvotes: 0
Reputation: 887453
Your view is declared as taking a set of Message
s.
You're trying to pass it a set of anonymous types.
As the error clearly states, it doesn't fit.
Instead, you should create a class to hold the data from the join, then declare the view as taking a set of that class.
(Views cannot easily use anonymously typed models)
Upvotes: 2