今天,在编写后台代码时,设计了几个数据库表,主键不一定是ID,主键存在SimulatorId,以及SimulatorId+SceneId复合主键的情况。
数据库实体建立好后,编译通过,在执行代码时报以下错误:
has no key defined. Define the key for this EntityType. ----没有定义主键
Use the ColumnAttribute or the HasKey method to specify an order for composite primary keys. ---多个主键的定义方式不对
报错的意思很明显,就是说实体没有主键和多个主键的定义方式不正确。
按照网上的信息,要在定义为主键的字段处增加[Key]修饰符,可是我加上后依旧报错,后来折腾了一番原来是发现没有引用using System.ComponentModel.DataAnnotations;
所以尽量这样写:
对于多个主键的方式,首先要在数据库实体中进行key定义:
其次,要在CmsDbContext中的OnModelCreating方法中再次申明主键:
modelBuilder.Entity<SimulatorScene>().HasKey(m => new { m.SceneId, m.SimulatorId });
解决!