How to Create Entity in ABP
The link is https://docs.abp.io/en/abp/latest/Entities
https://docs.abp.io/en/abp/latest/Repositories
Entities with GUID Keys
If your entity's Id type is Guid
, there are some good practices to implement:
Create a constructor that gets the Id as a parameter and passes to the base class.
If you don't set a GUID Id, ABP Framework sets it on save, but it is good to have a valid Id on the entity even before saving it to the database.
If you create an entity with a constructor that takes parameters, also create a
private
orprotected
empty constructor. This is used while your database provider reads your entity from the database (on deserialization).Don't use the
Guid.NewGuid()
to set the Id! Use theIGuidGenerator
service while passing the Id from the code that creates the entity.IGuidGenerator
optimized to generate sequential GUIDs, which is critical for clustered indexes in the relational databases.
public class Book : Entity<Guid>
{
public string Name { get; set; }
public float Price { get; set; }
protected Book()
{
}
public Book(Guid id)
: base(id)
{
}
}
Example of Application Service
public class BookAppService : ApplicationService, IBookAppService
{
private readonly IRepository<Book> _bookRepository;
public BookAppService(IRepository<Book> bookRepository)
{
_bookRepository = bookRepository;
}
public async Task CreateAsync(CreateBookDto input)
{
await _bookRepository.InsertAsync(
new Book(GuidGenerator.Create())
{
Name = input.Name,
Price = input.Price
}
);
}
}