gpt4 book ai didi

c# - 无法将 linq 结果隐式转换为 View 模型列表

转载 作者:行者123 更新时间:2023-11-30 12:26:08 27 4
gpt4 key购买 nike

我是 MVC 的新手,正在努力实现一个 ViewModel 来查询多个表。最初我的设置运行良好,但现在重新加载项目后出现编译错误,如下所示:

Cannot implicitly convert type 'System.Collections.Generic.List<CATEGORY>' to 'System.Collections.Generic.List<TestProject.Models.CATEGORY>'

View 模型代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TestProject.Models
{
public class COMPCATEGORY
{
public List<COMP> Comp { get; set; }
public List<CATEGORY> Category { get; set; }
}
}

Controller 代码:

namespace TestProject.Controllers
{
public class COMPsController : Controller
{
private mattbeaneyEntities1 db = new mattbeaneyEntities1();

// GET: COMPs
public ActionResult Index()
{
COMPCATEGORY viewModel = new COMPCATEGORY();
viewModel.Category = db.CATEGORies.ToList();
viewModel.Comp = db.COMPs.ToList();
return View(viewModel);
}

数据库上下文代码:

using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;


public partial class mattbeaneyEntities1 : DbContext
{
public mattbeaneyEntities1()
: base("name=mattbeaneyEntities1")
{
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}

public virtual DbSet<CATEGORY> CATEGORies { get; set; }
public virtual DbSet<COMP> COMPs { get; set; }
}

最佳答案

正如错误所暗示的那样,当我们只期望一种类型时,它遇到了两种同名类型的问题。 namespace 是我们的线索:

Cannot implicitly convert type 'System.Collections.Generic.List<CATEGORY>' to 'System.Collections.Generic.List<TestProject.Models.CATEGORY>'

通常在这种情况下我想检查几件事:

首先:是否有两个类共享相同的名称并属于不同的命名空间?随着项目的发展,这很容易做到!

其次:主项目命名空间有变化吗?有时由于一些重构,我们更改项目名称,然后在 bin 文件夹中得到两个 .dll 文件,其中包含我们所有类的副本 - 删除旧的!

关于c# - 无法将 linq 结果隐式转换为 View 模型列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29735841/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com