arsena
arsena

Reputation: 1975

Entity Framework Code-First Aproach and ModelValidationException

I'm building an MVC application and trying to use code-first aproach while building entities and database.

I get ModelValidationException when I run code. (Message: System.Data.Entity.ModelConfiguration.ModelValidationException' occurred in EntityFramework.dll but was not handled in user code)

This is code:

Controller:

public class HomeController : Controller {
    PhonesDB _db = new PhonesDB();

    public ActionResult Index() {
        var model = from b in _db.ProductList //Exception appears here
                    select b;
        return View(model);
    }
}

Models:

namespace SmartPhoneCatalog.Models {
    public class Products {
        public int ProductID { get; set; }
        public string Manufacturer { get; set; }
        public string Name { get; set; }
        //...
    }
}

namespace SmartPhoneCatalog.Models {
    public class PhonesDB:DbContext {
        public DbSet<Products> ProductList { get; set; }
    }
}

and this is the view:

@model IEnumerable<SmartPhoneCatalog.Models.Products>

@{
    ViewBag.Title = "Home";
}

@foreach (var item in Model) {
    <div>
        <h4>@item.Name</h4>
        <div>@item.Price</div>
        <hr/>
    </div>
}

Am I missing something?

Tried starting empty mvc application and then template but had the same problem on both one.

Replacing LINQ with var model = _db.ProductList.ToList(); didn't help. Also tried editing PhonesDB model(changes are in bold):

public **partial** class PhonesDB : DbContext {
    public PhonesDB():**base("PhonesDB")**{
    }

    **protected override void OnModelCreating(DbModelBuilder modelBuilder) {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }**

    public DbSet<Products> ProductList { get; set; }
}

still getting same exception. Any ideas how to fix it?

Upvotes: 2

Views: 4039

Answers (1)

Jason Millikan
Jason Millikan

Reputation: 597

That exception looks to be hiding the real exception. My guess is that the real exception is being thrown because you don't have a [Key] attribute on your ProductId field:

public class Products {
    [Key]
    public int ProductID { get; set; }
    public string Manufacturer { get; set; }
    public string Name { get; set; }
    //...
}

Here is some more info about the attributes used by Code First

Upvotes: 4

Related Questions