Question

I'm trying to make an abstraction over my DB Context layer (EntityFramework 2.0).

Car.DataContext
 ------------------- 
 public abstract class BaseCarContext : DbContext
    {
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Car>(e =>
            {
                e.ToTable("Car");             
            });
            modelBuilder.Entity<Car>(e => { e.ToTable("Cars"); });
        }
    }

     public class CarContext : BaseCarContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (optionsBuilder.IsConfigured)
                return;

            optionsBuilder.UseSqlServer(@"Server = xxxx; Database = xxxx; Trusted_Connection = True;");
        }

        public DbSet<Car> Cars { get; set; }        
    }

 Car.Logic
 ----------------
 public interface ICarService
 {
    GetCarResponse RetrieveCar(int id);
    void Save(int id);
    ...
 }

 public class CarService : ICarService
 {
    private readonly ICarService service;   
    // dbContext interface

    public CarService(ICarService service){
        this.service = service; 
        // injecting db context interface
    }

    public void Save(int id){
        ... saving using injected db context
        // injected db context.Insert(new Car{ Name = "Honda" });
    }
    ...
 }

How can I abstract this ef core 2 CarContext in order to use dbContext save

I tried to make an interface IDbContext which is implemented by CarContext but that way I cannot use dbContext.Cars.Insert because I'm not implementing dbContext cars collection don't have access to ef core methods and properties.

I can use of course concrete implementation but I'm trying to make an abstraction so I can use unit tests, ...

How would you do this?

1
0
5/4/2018 11:47:28 AM

Accepted Answer

First, you don't need an abstraction to unit test. EF Core is 100% test-friendly. Second, the only truly acceptable abstractions, in my opinion for EF (or really any ORM) is either a microservice or the CQRS/event sourcing patterns. Those actually add value in that they either fully abstract the dependency and/or solve real line-of-business problems. However, those patterns also require a significant amount of effort to implement correctly, and as such, typically are reserved for large, complex applications.

Long and short, just use EF directly unless you have a truly good reason not to. Testing is not a good reason.

4
5/4/2018 1:01:40 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow