我有以下控制器,我在其中创建BadgeAssignmentRepository
的实例。我试图在存储库的声明中传递我的dbcontext变量。但是我收到了A field initializer cannot reference the nonstatic field, method, or property EntryController.db
我不知道为什么我的代码错了。有人能帮助我吗?
这是控制器:
public class EntryController : Controller
{
public EchoLuMvcDbContext db = new EchoLuMvcDbContext();
private BadgeAssignmentRepository baRepository= new BadgeAssignmentRepository(db);
//this db is causing the trouble
这是存储库:
public class BadgeAssignmentRepository
{
public EchoLuMvcDbContext db { get; set; }
public BadgeAssignmentRepository(EchoLuMvcDbContext context)
{
this.db = context;
}
答案 0 :(得分:3)
如错误所示,您无法从字段初始值设定项访问其他字段。如果BadgeAssignmentRepository需要对db字段的引用,请在控制器的构造函数中初始化它,如下所示:
public class EntryController : Controller
{
public EchoLuMvcDbContext db = new EchoLuMvcDbContext();
private BadgeAssignmentRepository baRepository;
public EntryController() {
baRepository = new BadgeAssignmentRepository(db);
}
}