我正在制作一个非常简单的MVC应用程序来管理一些家居事物。之前,我总是在MVC模型生成器(GUI事物)中创建我的数据模型,或者导入已经创建的SQL表。即使键属性存在,也没有键定义的错误
这次,我想用代码优先的方法做到这一点。
我现向你的实体的例子:
public class Expense {
[Key]
public int ExpenseId;
public double ExpenseValue;
public DateTime ExpenseDate;
public string ExpenseDescription;
public ExpenseType ExpenseType;
public Currency ExpenseCurrency;
public List<ExpenseUser> Users;
}
而且我的DbContext派生类对象:
public class HawsContext : DbContext {
public DbSet<Expense> Expenses { get; set; }
public DbSet<ExpenseType> ExpenseTypes { get; set; }
public DbSet<ExpenseUser> ExpenseUsers { get; set; }
public ExpenseUser GetUserByUserName(string userName) {
return ExpenseUsers.Where(u => u.UserName == userName).FirstOrDefault();
}
}
任何时候,我实例收到以下错误的对象:
One or more validation errors were detected during model generation:
\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'Expense' has no key defined. Define the key for this EntityType. \tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'ExpenseType' has no key defined. Define the key for this EntityType. \tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'ExpenseUser' has no key defined. Define the key for this EntityType. \tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'Expenses' is based on type 'Expense' that has no keys defined. \tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'ExpenseTypes' is based on type 'ExpenseType' that has no keys defined. \tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'ExpenseUsers' is based on type 'ExpenseUser' that has no keys defined.
我在做什么错?我的所有实体都在其各自的键前面有[Key],所有内容都可以在没有错误或警告的情况下编译。它只有在我实例化上下文时才起作用,大概是在它即将创建时(它实际上还没有创建任何SQL表)。
在你的错误中,所有三个对象似乎都有这个问题......它不仅是费用。 – idipous