renakre
renakre

Reputation: 8291

Passing the dbcontext to the repository: A field initializer cannot reference the nonstatic field, method, or property

I have the following controller, in which I create an instance of the BadgeAssignmentRepository. I tried to pass the my dbcontext variable in the declaration of the repository. However I receive A field initializer cannot reference the nonstatic field, method, or property EntryController.db

I have no idea why my code is wrong. Can someone help me?

Here is the controller:

public class EntryController : Controller
{
    public EchoLuMvcDbContext db = new EchoLuMvcDbContext();
    private BadgeAssignmentRepository baRepository= new BadgeAssignmentRepository(db);
    //this db is causing the trouble

Here is the repository:

public class BadgeAssignmentRepository
{
    public EchoLuMvcDbContext db { get; set; }

    public BadgeAssignmentRepository(EchoLuMvcDbContext context)
    {
        this.db = context;
    }

Upvotes: 0

Views: 119

Answers (1)

Corey Smith
Corey Smith

Reputation: 1823

As the error says, you can't access another field from a field initializer. If your BadgeAssignmentRepository needs a reference to your db field, initialize it in your controller's constructor like this:

public class EntryController : Controller
{
    public EchoLuMvcDbContext db = new EchoLuMvcDbContext();
    private BadgeAssignmentRepository baRepository;

    public EntryController() {
        baRepository = new BadgeAssignmentRepository(db);
    }
}

Upvotes: 3

Related Questions