MVC没有密钥定义

时间:2012-07-29 00:33:40

标签: asp.net-mvc

我在MVC应用程序中收到此错误:

One or more validation errors were detected during model generation:

System.Data.Edm.EdmEntityType: : EntityType 'CustomerModel' has no key defined. Define the key for this EntityType.
System.Data.Edm.EdmEntitySet: EntityType: EntitySet �Customer� is based on type �CustomerModel� that has no keys defined.

我的客户模型如下所示:

public class CustomerModel
{
    public string Name { get; set; }
    public int CustomerID { get; set; }
    public string Address { get; set; }
}

public class CustomerContext : DbContext
{
    public DbSet<CustomerModel> Customer { get; set; }
}

1 个答案:

答案 0 :(得分:5)

默认情况下,Entity Framework假定您的模型类中存在一个名为Id的键属性。您的密钥属性称为CustomerID,因此Entity Framework无法找到它。

将密钥属性的名称从CustomerID更改为Id,或使用密钥属性修饰CustomerID属性:

public class CustomerModel
{
    public string Name { get; set; }

    [Key]
    public int CustomerID { get; set; }

    public string Address { get; set; }
}

public class CustomerContext : DbContext
{
    public DbSet<CustomerModel> Customer { get; set; }
}
相关问题