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

本文解决了Entity Framework中未正确识别'UserInfo'类主键的问题。通过将字段改为属性并命名为UserID,EF成功识别其为主键。

One or more validation errors were detected during model generation:

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

遇见这个问题,我觉得很奇特,因为事实上我已经为'UserInfo'这个类定义了[KEY]的类注释。

然后又提示我找不到Key。见下面的代码

复制代码
 1     public class UserInfo
 2     {
 3         [Key]
 4         public int UserID;
 5         public string UserName;
 6         public string Password;
 7         public int UseState;
 8         public string Email;
 9         public DateTime AddTime;
10         public int AddUser_ID;
11         public string ImgUrl;
12         public virtual UserType UserTypes { get; set; }
13     }
复制代码

后面在stackoverflow上找到了答案EF会自动识别一个实体的主键只要主键的名称符号 'Id'或 '实体名Id'. 另外,它必须声明成属性,访问权限必须是Public的。这个错误是因为我将UserId声明成了一个字段,只要修改成属性就OK了。修改后的代码如下所示。

 

复制代码
 1     public class UserInfo
 2     {
 3         [Key]
 4         public int UserID { get; set; }
 5         public string UserName { get; set; }
 6         public string Password { get; set; }
 7         public int UseState { get; set; }
 8         public string Email { get; set; }
 9         public DateTime AddTime { get; set; }
10         public int AddUser_ID { get; set; }
11         public string ImgUrl{ get; set; }
12         public virtual UserType UserTypes { get; set; }
13     }
复制代码

 

 

 

 

2013-01-10  16:50:05

本文转自陈哈哈博客园博客,原文链接http://www.cnblogs.com/kissazi2/archive/2013/01/10/2855082.html如需转载请自行联系原作者


kissazi2

@Getter @Setter @NoArgsConstructor @AllArgsConstructor @Table(name = "user_info") @Entity public class UserInfo { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false) private String username; @Column(nullable = false) private String password; @Column(nullable = false, unique = true) private String email; private String address; private Integer status = 0; } @Slf4j @RestController @RequestMapping("/admin") public class AdminController { @Autowired private AdminService adminService; @PostMapping("/add") public ResponseEntity<UserRegisterSuccessDTO> addUser(@Valid @RequestBody UserRegisterDTO userRegisterDTO) { try { UserRegisterSuccessDTO response = adminService.addUser(userRegisterDTO); log.info("{} added", userRegisterDTO.getUsername()); return ResponseEntity.ok(response); } catch (UnauthorizedException e) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null); } } @DeleteMapping("/delete") public ResponseEntity<ReponseDTO> deleteUserByEmail(@Valid @RequestBody RequestDTO requestDTO) { try { ReponseDTO response = adminService.deleteUserByEmail(requestDTO.getEmail()); log.info("{} deleted", response.getUsername()); return ResponseEntity.ok(response); } catch (UnauthorizedException e) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null); } } @PutMapping("/update") public ResponseEntity<ReponseDTO> updateUser(@Valid @RequestBody UserDTO userDTO) { try { ReponseDTO response = adminService.updateUser(userDTO); log.info("{} updated", response.getUsername()); return ResponseEntity.ok(response); } catch (UnauthorizedException e) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null); } } @GetMapping("/get") public ResponseEntity<UserInfo> getUserByEmail(@Valid @RequestBody RequestDTO requestDTO) { try { UserInfo response = adminService.getUserByEmail(requestDTO.getEmail()); log.info("{} searched", response.getUsername()); return ResponseEntity.ok(response); } catch (UnauthorizedException e) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null); } } } @Slf4j @Service public class AdminServiceImpl implements AdminService{ @Autowired private UserRepository userRepository; @Value("${app.max-users}") private long maxUserCount; @Override public UserRegisterSuccessDTO addUser(UserRegisterDTO userRegisterDTO) { // 检查是否达到最大用户数 long currentCount = userRepository.count(); if(currentCount >= maxUserCount) { log.error("Maximum user limit reached"); throw new UnauthorizedException("Maximum user limit reached"); } // 检查邮箱是否重复 if (userRepository.existsByEmail(userRegisterDTO.getEmail())) { log.error("Email already exists"); throw new UnauthorizedException("Email already exists"); } // 创建用户 UserInfo user = new UserInfo(); user.setUsername(userRegisterDTO.getUsername()); user.setPassword(userRegisterDTO.getPassword()); user.setEmail(userRegisterDTO.getEmail()); user.setAddress(userRegisterDTO.getAddress()); userRepository.save(user); return new UserRegisterSuccessDTO("User added successfully", user.getId()); } @Transactional @Override public ReponseDTO deleteUserByEmail(String email) { if (!userRepository.existsByEmail(email)) { log.error("User not existed"); throw new RuntimeException("User not existed"); } UserInfo user = userRepository.findByEmail(email).get(); userRepository.deleteByEmail(email); return new ReponseDTO(user.getUsername()); } @Override public ReponseDTO updateUser(UserDTO userDTO) { Optional<UserInfo> userOpt = userRepository.findByEmail(userDTO.getEmail()); UserInfo user = userOpt.get(); if (userDTO.getUsername() != null && !userDTO.getUsername().trim().isEmpty()) { user.setUsername(userDTO.getUsername()); } if (userDTO.getPassword() != null && !userDTO.getPassword().trim().isEmpty()) { user.setPassword(userDTO.getPassword()); } if (userDTO.getEmail() != null && !userDTO.getEmail().trim().isEmpty()) { user.setEmail(userDTO.getEmail()); } if (userDTO.getAddress() != null && !userDTO.getAddress().trim().isEmpty()) { user.setAddress(userDTO.getAddress()); } userRepository.save(user); return new ReponseDTO(user.getUsername()); } @Override public UserInfo getUserByEmail(String email) { if (!userRepository.existsByEmail(email)) { log.error("User not existed"); throw new RuntimeException("User not existed"); } return userRepository.findByEmail(email).get(); } } public interface UserRepository extends JpaRepository<UserInfo, Long> { boolean existsByEmail(String email); Optional<UserInfo> findByEmail(String email); @Override long count(); void deleteByEmail(String email); } spring: profile: mysql datasource: url: jdbc:mysql://localhost:3306/mysql?useSSL=false&serverTimezone=GMT%2B8 username: root password: 123032 jpa: hibernate: ddl-auto: update show-sql: true properties: hibernate: dialect: org.hibernate.dialect.MySQL8Dialect management: endpoints: web: exposure: include: "*" endpoint: health: show-details: always app: max-users: 20 已经使用mysql实现了用户的增删改查,现在想切换cassandra数据库来实现相应功能,并且在Controller层不变的情况下,实现通过简单修改配置后,更换不同的数据源,相关代码和配置如上,应该怎么加代码和改配置
最新发布
08-29
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值