1

我在我的 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; }
}
4

1 回答 1

7

默认情况下,Entity Framework 假定模型类中存在一个名为 Id 的关键属性。您的关键属性称为 CustomerID,因此实体框架找不到它。

将您的关键属性的名称从 CustomerID 更改为 Id,或者使用Key属性装饰 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; }
}
于 2012-07-29T00:43:29.183 回答