Abp教程—使用自定义主键

Table of contents

ABP 框架默认使用 Id 作为领域模型的主键,其类型为 Guid。但实际开发过程中,有些表的主键可能需要使用其他类型如 longstring等等,接下来我们就来了解在 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 将 Idset 方法设置为 protected 级别,我们只能从领域实体类中对 Id 进行 set,建议使用构造函数对 Id 进行赋值。 否则在新增数据时会提示 Id is null 的异常。