2

If I was using the .NET framework version of EF, I'd simply do using(var db = new dbContext()) and I'd be able to instantiate a new context and insert data using db.<tableName>.add()

However, this doesn't work for .NET core. When I attempt to instantiate a new context, I get an error message requiring that a

DbContextOptions object is passed through to the context object to instantiate it.

This is DbContext class:

public SolicitorContext(DbContextOptions<SolicitorContext> options) : base(options)
{
}

Obviously the options object needs to be passed through here to init the object.

2
  • What's your question? Yes you need to supply options to the constructor. Commented Oct 15, 2018 at 15:12
  • It has nothing to do with Full/Core frameworks. EF Core also supports parameterless constructor, just add it to your db context class, e.g. public SolicitorContext() { } Commented Oct 15, 2018 at 15:13

2 Answers 2

2
var dbOptions = new DbContextOptionsBuilder<YOURCONTEXT>()
            .UseSqlServer(connectionString: Environment.GetEnvironmentVariable("YOURCONNSTRING"))
            .Options;

using (var yourDB = new YOURCONTEXT(dbOptions))
{
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the DbContextOptionsBuilder:

DbContextOptionsBuilder<dbContext> dbContextOptionsBuilder = new DbContextOptionsBuilder<dbContext>();
dbContextOptionsBuilder.UseSqlServer("MyConnectionString");

And pass the dbContextOptionsBuilder.Options as the parameter options when initializing your context:

using (var db = new dbContext(dbContextOptionsBuilder.Options))

Comments

Your Answer

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