Z
Z
z_a_p_a_r_a2018-11-18 00:59:27
ASP.NET
z_a_p_a_r_a, 2018-11-18 00:59:27

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; }

    }

To do this, I create a validation attribute ... but I can’t create an instance of the context in any way to pull out all the NAME fields from there.
I try like this: But then it requires an argument, because it goes to the constructor with an argument ... what to pass to it?
var db = new InstituteContext();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
eRKa, 2018-11-18
@z_a_p_a_r_a

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 question

Ask a Question

731 491 924 answers to any question