I'm getting the following error:
One or more validation errors were detected during model generation:
\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'UserAccount' has no key defined. Define the key for this EntityType.
\tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'UserAccounts' is based on type 'UserAccount' that has no keys defined.
This error is triggered by the code:
_Db.Database.Initialize(true);
I assume it's not picking up the [Key] attribute on the model for some reason. Originally when I attempted to run the code I hadn't added the key attribute, could this mean something has been created / cached which is preventing this key being applied?
The MVC4 project is almost a blank setup aside from including Entity Framework 5
Model Code
public class AccountContext: DbContext
{
public AccountContext()
: base("DefaultConnection")
{
}
public DbSet<UserAccount> UserAccounts { get; set; }
}
[Table("UserAccount")]
public class UserAccount
{
[Key]
[Required]
public string Username;
[Required]
[DataType(DataType.Password)]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
public string Password;
public string Name;
public string Surname;
[Required]
public string Email;
}
Global.asax Initialization
Database.SetInitializer(new DropCreateDatabaseAlways<AccountContext>());
var _Db = new AccountContext();
_Db.Database.Initialize(true);
I've already done some searching and understand the naming conventions e.g. Id / UserId etc. However i'd like to explicitly use [Key] and call the field Username.
I believe EF only allows mapping to properties, not fields as you have used.
Try changing:
[Key]
[Required]
public string Username;
to
[Key]
[Required]
public string Username { get; set; }
I'd like to add that if you happen to forget to make the target key property public, you will receive this same error. I came here for the same key error and noticed that I was lacking the "public" attribute. I added it and my error went away.
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