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

Discussion of open issues, suggestions and bugs regarding Entity Developer - ORM modeling and code generation tool
Post Reply
RobertK
Posts: 56
Joined: Thu 02 Mar 2017 05:44

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

Post by RobertK » Mon 27 Nov 2017 23:56

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

Shalex
Site Admin
Posts: 8247
Joined: Thu 14 Aug 2008 12:44

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

Post by Shalex » Thu 30 Nov 2017 14:50

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

RobertK
Posts: 56
Joined: Thu 02 Mar 2017 05:44

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

Post by RobertK » Fri 01 Dec 2017 02:27

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
            }

Post Reply