当我更改查询时出现错误。你能帮忙吗?
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);
}
这是aspx文件的第一行
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MyProject.Models.Message>>" %>
这是错误
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]'.
答案 0 :(得分:2)
您的观点被宣布为采用一组Message
s
你试图传递一组匿名类型。
由于错误明确指出,它不合适。
相反,您应该创建一个类来保存连接中的数据,然后将视图声明为采用该类的一组。
(视图不能轻易使用匿名类型模型)
答案 1 :(得分:0)
因为您加入了创建匿名类型的行为,所以需要执行
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 { ... .. .. } );
答案 2 :(得分:0)
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);
}
或者如果您还需要类别,则应更改视图模型类型
编辑:
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);
}
和模型类型应该是MessageWithCategories(必须创建此类)