1

I am building a multi-tenanted application. The code is shared but each client has a different database. I have code that determines the specific client's database connection string (based on an API key they are using).

I want to initialise the context using this connection string.

I approached this by passing the string to the repository constructor in the hope I could then reuse it for the context constructor but I am getting the error:

A field initializer cannot reference the non-static field, method, or property...

when I attempt to initialize an Entity Framework database context using a connection string that I have previously passed into the Repository constructor.

I have researched and understand the error (you can't initialize one instance member using an other instance member, as it may not be available at that time) but I am unsure how to work my way around it.

What I am trying to achieve is self-evident from the code:

public class GlobalCompanyRepository : IGlobalCompanyRepository
{
    private readonly string _dbConnectionString;

    public GlobalCompanyRepository(string dbConnectionString)
    {
        _dbConnectionString = dbConnectionString;
    }

    public IntrinsicDbContext dbContext = new IntrinsicDbContext(_dbConnectionString);
    public void Add(GlobalCompany entity)
    {
        dbContext.GlobalCompanies.Add(entity);
        dbContext.SaveChanges();
    }
}

2 Answers 2

2

You are trying to initialize your field dbContext

public IntrinsicDbContext dbContext = new   IntrinsicDbContext(_dbConnectionString);

Before _dbConnectionString has been given a value.

You can move the initialization into the constructor.

Sign up to request clarification or add additional context in comments.

Comments

0

You can initialize the dbContext in the constructor when _dbConnectingString has a value:

public class GlobalCompanyRepository : IGlobalCompanyRepository
{
    private readonly string _dbConnectionString;

    public GlobalCompanyRepository(string dbConnectionString)
    {
        _dbConnectionString = dbConnectionString;
        dbContext = new IntrinsicDbContext(_dbConnectionString);
    }

    public IntrinsicDbContext dbContext;
    public void Add(GlobalCompany entity)
    {
        dbContext.GlobalCompanies.Add(entity);
        dbContext.SaveChanges();
    }
}

1 Comment

Perfect! Exactly what I needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.