我正在尝试对我的数据库上下文层(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 core 2CarContext
以便使用dbContext
save
我试图制作一个IDbContext
由其实现的接口,CarContext
但我无法使用这种方式,dbContext.Cars.Insert
因为我没有实现 dbContext 汽车集合无法访问 ef 核心方法和属性。
我当然可以使用具体的实现,但我正在尝试进行抽象,以便我可以使用单元测试,...
你会怎么做?
首先,您不需要对单元测试进行抽象。EF Core 100% 测试友好。其次,在我看来,对于 EF(或任何ORM)来说,唯一真正可接受的抽象要么是微服务,要么是 CQRS/事件源模式。这些实际上增加了价值,因为它们要么完全抽象依赖项和/或解决实际的业务线问题。但是,这些模式也需要付出大量努力才能正确实现,因此,通常为大型、复杂的应用程序保留。
总而言之,除非您有充分的理由不使用,否则请直接使用 EF。测试不是一个很好的理由。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句