Answer the question
In order to leave comments, you need to log in
How to instantiate a database context?
Good day.
My next task is to check the model field for uniqueness when adding it to the database.
Context:
public class InstituteContext : DbContext
{
public InstituteContext (DbContextOptions<InstituteContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Department>().HasIndex(p => p.Name).IsUnique();
}
public DbSet<Institute.Models.Department> Department { get; set; }
}
var db = new InstituteContext();
Answer the question
In order to leave comments, you need to log in
An instance of DbContextOptions must be passed to the constructor.
This can be done either by hand, or using the DI
dock
. In a simple version, by hand, it will look like this:
var timeout = 600;
var optionsBuilder = new DbContextOptionsBuilder<InstituteContext>()
.UseSqlServer(new SqlConnection(connectionString), opt =>
{
opt.CommandTimeout(timeout);
});
using (var context = new InstituteContext (optionsBuilder.Options))
{
// your code
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question