Mic*_*ers 1 c# dependency-injection layered dbcontext asp.net-core
我有一个使用Asp.Net MVC Core 2.1构建的3层(Presentation - Business - Data)应用程序
在我的Presentation层中,我有一个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
}
Run Code Online (Sandbox Code Playgroud)
所述类在Startup.cs类中注入(也在表示层中):
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>().AddEntityFrameworkStores<ApplicationDbContext>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest);
Run Code Online (Sandbox Code Playgroud)
我现在想在数据层中使用这个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();
}
//...
}
}
Run Code Online (Sandbox Code Playgroud)
如果您想在PizzaShop.Data项目中保留所有与数据库相关的内容,那么您ApplicationDbContext不属于您的Web项目.它属于您的PizzaShop.Data项目.
然后,您从Web项目中引用您的PizzaShop.Data项目.
| 归档时间: |
|
| 查看次数: |
175 次 |
| 最近记录: |