I'm new to MVC as well as the entity framework. I searched lot and find few similar questions (e.g. Entity Type Has No Key Defined) but they don't solve my problem.
namespace MvcAppInvoice.Models
{
public class Customer
{
public int CustomerID { get; set; }
public string FirstName { get; set; }
public string SurName { get; set; }
public virtual CustomerType Type { get; set; }
}
public class CustomerType
{
public int TypeId { get; set; }
public string TypeName { get; set; }
public virtual ICollection<Customer> customers { get; set; }
}
}
When I try to add the controller it gives the following error:
Add namespace
using System.ComponentModel.DataAnnotations;
Add key attribute to your CustomerID like this
[Key]
public int CustomerID { get; set; }
then build the application and try to add controller. This will work
Typically, code first by convention implicitely sets key for entity type if property is named Id
or TypeName+Id
. In your case, TypeId
is neither of them, so you should explicitely mark it as key, using KeyAttribute or with fluent syntax, using EntityTypeConfiguration.HasKey Method
I had the same problem. I restarted the project 3 times before I found the solution that worked for me. I had a public class that I manually created called UserContext. When I ran the wizard to add an ADO class the wizard generated a partial class of UserContext. I deleted my usercontext class and I modified the class that VS generated for me.
namespace UserLayer.Models
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public class UserContext : DbContext
{
public DbSet<UserDetail> UserDetails { get; set; }
}
}
Now it may have had worked without the modification. Perhaps deleting my version of the class would have work. I do not know. In retropect I encountered your error when I tried to add the controller. I suspect this is a bug in VS2012 because a partial class and a public class of the same name can exist. The intent is to allow the programmer to extend the definition of the partial class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With