Skip to content

jaka-logar/LSolutions.ObjectContext

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

LSolutions.ObjectContext

ObjectContext implementation for EntityFrameworkCore based on BaseEntity and IRepository.
Implementation taken from NopCommerce (https://github.com/nopSolutions/nopCommerce).

Build status contributions welcome

Packed as two NuGet packages in case you have database related code in separate project:

  • LSolutions.EntityRepository NuGet
  • LSolutions.EfObjectContext NuGet

Usage

  1. 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; }
    }
  1. Your ObjectContext implementation must extend BaseObjectContext.
  2. Register ObjectContext and EfRepository.
    services.AddDbContext<IDbContext, ObjectContext>();
    services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));
  1. 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);
        }
    }
  1. 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);
        }
    } 

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages