Reputation: 41
I'm new to MVC and struggling to implement a ViewModel to query multiple tables. Initially my setup worked perfectly but now having reloaded the project I am getting a compilation error as copied below:
Cannot implicitly convert type 'System.Collections.Generic.List<CATEGORY>' to 'System.Collections.Generic.List<TestProject.Models.CATEGORY>'
ViewModel code:
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 Code:
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);
}
DB Context code:
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; }
}
Upvotes: 4
Views: 1111
Reputation: 10100
As the error suggests it is having trouble with two types by the same name, when we were only expecting one. The namespace is our clue here:
Cannot implicitly convert type 'System.Collections.Generic.List<CATEGORY>' to 'System.Collections.Generic.List<TestProject.Models.CATEGORY>'
Usually there are a couple of things I like to check in this case:
Firstly: are there two classes that share the same name and belong to different namespaces? It's quite easy to do as your project grows!
Secondary: has the main project namespace changed? Sometimes due to a bit of refactoring we change the project name and then end up with two .dll files in the bin folder, which hold duplicate of all our classes - delete the old one!
Upvotes: 2