我收到以下错误: 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
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.
此错误由代码触发:
_Db.Database.Initialize(true);
我假设由于某种原因它没有在模型上获取[Key]属性.最初当我尝试运行代码时,我没有添加key属性,这是否意味着已经创建/缓存了某些东西,这阻止了这个密钥的应用?
除了包含Entity Framework 5之外,MVC4项目几乎是一个空白的设置
型号代码
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初始化
Database.SetInitializer(new DropCreateDatabaseAlways<AccountContext>()); var _Db = new AccountContext(); _Db.Database.Initialize(true);
我已经做了一些搜索并理解命名约定,例如Id / UserId等但是我想明确使用[Key]并调用字段Username.
我相信EF只允许映射到属性,而不是你使用过的字段.尝试改变:
[Key] [Required] public string Username;
至
[Key]
[Required]
public string Username { get; set; }
