我有一个使用 Asp.Net MVC Core 2.1 构建的 3 层应用程序(演示 - 业务 - 数据)
在我的表示层中,我有一个 ApplicationDbContext 类,它实例化并填充一个测试数据库:
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
SeedData(builder);
}
// Database Tables
public DbSet<Customer> Customers { get; set; }
public DbSet<Ingredient> Ingredients { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderDetail> OrderDetails { get; set; }
public DbSet<Pizza> Pizzas { get; set; }
public DbSet<PizzaIngredient> PizzaIngredients { get; set; }
// Fill Database with sample data
private void SeedData(ModelBuilder builder)
{
// Seed data
}
所述类被注入到 Startup.cs 类中(也在表示层中):
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>().AddEntityFrameworkStores<ApplicationDbContext>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest);
我现在想在数据层中使用这个 ApplicationDbContext 类来保持代码分离。我最好怎么做?通过构造函数注入类似乎不起作用(严重代码描述项目文件行抑制状态错误 CS0246 找不到类型或命名空间名称“ApplicationDbContext”(您是否缺少 using 指令或程序集引用?))
namespace PizzaShop.Data.Repositories
{
public class PizzaRepo : IPizzaRepo
{
private readonly ApplicationDbContext _context;
public PizzaRepo(ApplicationDbContext context)
{
_context = context;
}
public async Task<int> AddEntityAsync(Pizza entity)
{
_context.Pizzas.Add(entity);
return await _context.SaveChangesAsync();
}
//...
}
}