我正在尝试创建一个简单的Asp.NET MVC数据库,用户可以在其中创建帐户,为食谱创建类别,然后输入他们的食谱并将其归档到他们选择的类别中。但是,当我尝试运行测试以查看是否可以访问我的类别列表(我还可以添加类别)时,我收到以下错误消息:
InvalidOperationException:无法解析类型' LC101Project2017.Data.RecipeDbContext'在尝试激活LC101Project2017.Controllers.CategoryController'。
我是C#的新手,对于我做错了什么完全感到困惑。这是我的代码:
控制器:(CategoryController.cs)
public class CategoryController : Controller
{
private readonly RecipeDbContext context;
public CategoryController(RecipeDbContext dbContext)
{
context = dbContext;
}
public IActionResult Index()
{
List<RecipeCategory> categories = context.Categories.ToList();
return View(categories);
}
public IActionResult Add()
{
AddCategoryViewModel addCategoryViewModel = new AddCategoryViewModel();
return View(addCategoryViewModel);
}
[HttpPost]
public IActionResult Add(AddCategoryViewModel addCategoryViewModel)
{
if (ModelState.IsValid)
{
RecipeCategory newCategory = new RecipeCategory
{
Name = addCategoryViewModel.Name
};
context.Categories.Add(newCategory);
context.SaveChanges();
CategoryController: return Redirect("/Category");
};
return View(addCategoryViewModel);
}
}
数据库(RecipeDbContext.cs)
public class RecipeDbContext : DbContext
{
public DbSet<Recipe> Recipes { get; set; }
public DbSet<RecipeCategory> Categories { get; set; }
}
模型(RecipeCategory.cs)
public class RecipeCategory
{
public int ID { get; set; }
public string Name { get; set; }
public IList<RecipeCategory> RecipeCategories { get; set; }
}
答案 0 :(得分:2)
检查您是否已在Startup.cs中的ConfigureServices方法中配置使用DbContext,RecipeDbContext
该方法应如下所示;
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<RecipeDbContext >(options =>
options.UseSqlServer(Configuration.GetConnectionString("ConnectionStringName")));
}
更新了答案以回应@Mel Mason的评论
您需要声明一个接受DbContextOptions<RecipeDbContext>
。
public class RecipeDbContext : DbContext
{
public DbSet<Recipe> Recipes { get; set; }
public DbSet<RecipeCategory> Categories { get; set; }
public RecipeDbContext(DbContextOptions<RecipeDbContext> options)
: base(options)
{ }
}
您还可以查看官方文档:
https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-strings
希望这有帮助。