Skip to content

Generic repository pattern for aspnetcore & EF Core, with scoped Context

License

Notifications You must be signed in to change notification settings

TheTrigger/F2.Repository

Repository files navigation

F2.Repository

Codacy Badge

Simple definitions for repository pattern

Getting started

1. Install Nuget package F2.Repository

Install-Package F2.Repository

2. Implement IEntity<TKey> on your models

Or, you can create your own BaseEntity:

public abstract class BaseEntity : IEntity<Guid>, ITimestampedEntity
{
	public Guid Id { get; set; }
	public DateTime CreatedAt { get; set; }
	public DateTime UpdatedAt { get; set; }
}
public class Book : BaseEntity
{
    public string Title { get; set; }

    public string Isbn { get; set; }

	public virtual ICollection<Author> Authors { get; set; }
}

Create your configuration (see example)

public class BookEntityConfiguration : IEntityTypeConfiguration<Book>
{
	public void Configure(EntityTypeBuilder<Book> builder)
	{
		builder.UseAutoGeneratedId();
		builder.UseTimestampedProperty();

		builder.HasMany(s => s.Authors).WithMany(s => s.Books);
	}
}

3. Implement your repository

GenericEntityRepository<TEntityType> or GenericRepository<TEntityType> abstracts

using F2.Repository.Abstracts;

public class CustomerRepository : GenericEntityRepository<Customer>
{
    public CustomerRepository(YourDbContext context) : base(context)
    {
    }
}

4. Create Database Context Scope

public class YourDbScope : DbContextScope<YourDbContext>
{
    public YourDbScope(YourDbContext context) : base(context)
    {
        YourRepository = yourRepository;
    }

    public YourRepository YourRepository { get; }
}

5. Register Scope and repositories to DI

All repositories will automatically registered for DI

services.AddDatabaseScope<YourDbContext>();
// ... services.AddDbContext<AutomateContext>(opts => opts.UseSqlServer(_configuration.GetConnectionString("SqlConnection"));

About

Generic repository pattern for aspnetcore & EF Core, with scoped Context

Topics

Resources

License

Stars

Watchers

Forks

Languages