1. 程式人生 > >EntityType 'User' has no key defined. Define the key for this EntityType.

EntityType 'User' has no key defined. Define the key for this EntityType.

在asp.net mvc 專案中新建立實體EF後在讀取時遇到的一個問題:

One or more validation errors were detected during model generation:
SportsStore.Domain.Concrete.User: : EntityType 'User' has no key defined. Define the key for this EntityType.
Users: EntityType: EntitySet 'Users' is based on type 'User' that has no keys defined.

從語句上看是說沒有key的定義,也就是說你的資料庫中設定的主鍵你沒有在實體中定義或者是你的這個表中沒有主鍵;

若沒有定義主鍵,將主鍵在類中定義即可;

若資料庫表中沒有主鍵,也有一種解決辦法,就是給定義的類中定義一個假的主鍵:

public class User
    {
        //[Key]
        public int id { get; set; }
        public string username { get; set; }
        public string password { get; set; }
        public int limit { get; set; }
        public DateTime time { get; set; }
    }

比如上面的類中,如果沒有主鍵id的定義,可以選擇下面任意一個屬性新增一個[Key]的定義:

此時需要using System.ComponentModel.DataAnnotations;

  public class User
    {
        [Key]
        public string username { get; set; }
        public string password { get; set; }
        public int limit { get; set; }
        public DateTime time { get; set; }
    }

本文遇到的問題已解決。