2

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?

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

omg, such a simple solution, I was looking for it all day long. thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.