user10506386
user10506386

Reputation:

How do I insert data into my database using Entity Framework .NET Core?

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.

Upvotes: 2

Views: 1425

Answers (2)

Askar Rayapov
Askar Rayapov

Reputation: 168

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

using (var yourDB = new YOURCONTEXT(dbOptions))
{
}

Upvotes: 2

kaffekopp
kaffekopp

Reputation: 2619

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))

Upvotes: 0

Related Questions