Page 1 of 1

How do you pass a connection string into "dbcontext"?

Posted: Mon 27 Nov 2017 23:56
by RobertK
You can use Entity Framework as such, but how do you pass a connection string to "MyDbContext"?

Code: Select all

                using (var context = new MyDbContext())
                {
                    var myItem= new Item
                    {
                        Name = "hello"
                    };
                    context.Add(myItem);
                    context.SaveChanges();
                }

Re: How do you pass a connection string into "dbcontext"?

Posted: Thu 30 Nov 2017 14:50
by Shalex
A predefined EF Core template generates two constructors:

Code: Select all

        public ModelContext() :
            base()
        {
            OnCreated();
        }

        public ModelContext(DbContextOptions<ModelContext> options) :
            base(options)
        {
            OnCreated();
        }
So, you can specify a connection string with the second constructor in the following way:

Code: Select all

            var optionsBuilder = new DbContextOptionsBuilder();
            optionsBuilder.UseSqlServer(@"your_connection_string_here");
            var context = new ModelContext(optionsBuilder.Options);

Re: How do you pass a connection string into "dbcontext"?

Posted: Fri 01 Dec 2017 02:27
by RobertK
Shalex wrote:A predefined EF Core template generates two constructors:
thanks

Code: Select all

            var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
            optionsBuilder.UseNpgsql(@"your_connection_string_here");

            using (var appDbcontext = new ApplicationDbContext(optionsBuilder.Options))
            {
                // do stuff
            }