我试图对我的DB上下文层(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" });
}
...
}如何抽象这个ef核心2 CarContext以便使用dbContext保存
我试图创建一个由CarContext实现的接口CarContext,但是那样的话,我不能使用dbContext.Cars.Insert,因为我没有实现dbContext,cars集合没有访问ef核心方法和属性的权限。
当然,我可以使用具体的实现,但是我正在尝试进行抽象,所以我可以使用单元测试,.
你会怎么做?
发布于 2018-05-04 13:01:40
首先,您不需要对单元测试进行抽象。EF核心100%测试友好.其次,在我看来,对于EF (或任何ORM)来说,唯一真正可接受的抽象是一个微服务或CQRS/事件源模式。它们实际上增加了价值,因为它们要么完全抽象了依赖关系,要么解决了实际的业务问题。然而,这些模式也需要大量的努力才能正确实现,因此,通常是为大型复杂应用程序保留的。
长和短,只要直接使用EF,除非你有一个真正的理由不这样做。测试不是一个很好的理由。
https://stackoverflow.com/questions/50174203
复制相似问题