ObjectContext implementation for EntityFrameworkCore based on BaseEntity and IRepository.
Implementation taken from NopCommerce (https://github.com/nopSolutions/nopCommerce).
Packed as two NuGet packages in case you have database related code in separate project:
- Every entity class must extend BaseEntity.
public class Product : BaseEntity
{
public int Id { get; set; }
public string Sku { get; set; }
public string Ean { get; set; }
}
- Your ObjectContext implementation must extend BaseObjectContext.
- Register ObjectContext and EfRepository.
services.AddDbContext<IDbContext, ObjectContext>();
services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));
- Create entities database mapping using fluent API.
internal class ProductMap : CustomEntityTypeConfiguration<Product>
{
public override void Configure(EntityTypeBuilder<Product> builder)
{
builder.ToTable("Product");
builder.HasKey(x => x.Id);
builder.Property(x => x.Sku)
.HasMaxLength(15)
.IsRequired();
builder.Property(x => x.Ean)
.HasMaxLength(15)
.IsRequired();
base.Configure(builder);
}
}
- Implement database queries
public class ProductService : IProductService
{
private readonly IRepository<Product> _productRepository;
public ProductService(IRepository<Product> productRepository)
{
_productRepository = productRepository;
}
public virtual Product GetProductById(int id)
{
IQueryable<Product> query =
from p in _productRepository.Table
where p.Id == id
select p;
return query.FirstOrDefault();
}
public virtual void InsertProduct(Product product)
{
_productRepository.Insert(product);
}
}