Abp教程—使用自定义主键
Science is gold.
ABP 框架默认使用
Id作为领域模型的主键,其类型为Guid。但实际开发过程中,有些表的主键可能需要使用其他类型如long、string等等,接下来我们就来了解在 ABP 中如何使用自定义主键
修改领域模型
这里我们将主键类型修改为 long 类型
public class User : BasicAggregateRoot<long>
{
[Key]
// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] //Set Id auto increase
public override long Id { get; protected set; }
public User(long id): base(id)
{
}
}
仓储类使用
Route("/api/user")]
public class UserAppService : BookStoreAppService, ITestAppService
{
private readonly IRepository<User, long> _userRepository;
public TestAppService(IRepository<User, long> testRepository)
{
_userRepository = testRepository;
}
}
注意:创建
User对象时,如果主键不是自增需要对Id赋值时,不能直接在外部对Id进行赋值操作,这是因为 ABP 将Id的set方法设置为protected级别,我们只能从领域实体类中对Id进行set,建议使用构造函数对Id进行赋值。 否则在新增数据时会提示Id is null的异常。