【发布时间】:2018-12-17 13:09:28
【问题描述】:
我有一个使用 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();
}
//...
}
}
【问题讨论】:
-
这个错误发生在设计时还是运行时?这些层是在不同的程序集中分开的还是只是一个应用程序?在构造函数中传递上下文是要走的路,所以这应该可行。
-
嗨。错误发生在设计时。这些层都包含在同一个解决方案文件中,每个都包含在一个项目中。我已经包含了架构的屏幕截图。
标签: c# asp.net-core dependency-injection dbcontext layered