c#lambda表达式错误..这本字典需要类型为的模型项

本文关键字:类型 模型 错误 表达式 字典 c#lambda | 更新日期: 2023-09-27 18:16:21

当我更改查询时,我得到了一个错误。你能帮忙吗?

    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]'.

c#lambda表达式错误..这本字典需要类型为的模型项

您的视图被声明为采用一组Message s。
您正试图向它传递一组匿名类型。

正如错误明确指出的那样,它不适合。

相反,您应该创建一个类来保存联接中的数据,然后将视图声明为接受该类的集合
(视图无法轻松使用匿名类型的模型(

因为你的加入是你创建的匿名类型,你需要做

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 { ... .. ..  } );
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(必须创建此类(