Repository navigation
Entity Framework Core Example 1
Harshit Gindra edited this page Mar 13, 2021
·
1 revision
Here's an example of using Crystal.EntityFrameworkCore library in your project.
Here we will be using only one entity Book.cs
public class Book
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int BookId { get; set; }
public string Name { get; set; }
}
Here, the context uses sqlite as the database.
public class SampleContext : BaseContext
{
public virtual DbSet<Book> Books { get; set; }
public SampleContext()
{
this.Database?.EnsureCreated();
}
public SampleContext(DbContextOptions<SampleContext> options)
: base(options)
{
this.Database?.EnsureCreated();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("filename=sample.sqlite");
base.OnConfiguring(optionsBuilder);
}
}
The unit of work can be configured into the service collection by adding the following line in your Startup.cs file
//***
//*** Configuring unit of work services
//***
services.ConfigureUnitOfWork<SampleContext>();
private readonly IBaseUowRepository _uowRepository;
public BookController(IBaseUowRepository uowRepository)
{
_uowRepository = uowRepository;
}
A simple get operation to retrieve records from the database based on filters
//***
//*** Get all books from the database
//***
var data = await _uowRepository.Repository<Book>().GetAsync();
//***
//*** Find the book from the database based on primary id
//***
var book = await _uowRepository.Repository<Book>().FindAsync(id);
//***
//*** Add/insert new book to the database
//***
await _uowRepository.Repository<Book>().InsertAsync(book);
await _uowRepository.CommitAsync();
//***
//*** Update book details in the database
//***
await _uowRepository.Repository<Book>().UpdateAsync(book);
await _uowRepository.CommitAsync();
//***
//*** Delete the book from the database based on primary id
//***
await _uowRepository.Repository<Book>().DeleteAsync(id);
await _uowRepository.CommitAsync();
As IBaseUowRepository is registered into the service collection as Transient, all the repositories and database context will automatically be disposed when IBaseUowRepository is disposed