Skip to content

Add DbContextOptions support for factory methods #562

@LarryWMSN

Description

@LarryWMSN

In order to handle configurable database options while using the factory methods I think it the following template would create the methods that most developers would want to have available, including use with DI:

public override string DatabaseContextFactory()
    {
            return @"
{{classModifier}} class {{contextName}}Factory : IDesignTimeDbContextFactory<{{contextName}}>{{#newline}}
{{{#newline}}
    private readonly DbContextOptions<{{contextName}}> Options;{{#newline}}
{{#newline}}
    public {{contextName}}Factory(){{#newline}}
    {{{#newline}}
    }{{#newline}}
{{#newline}}
    public {{contextName}}Factory(DbContextOptions<{{contextName}}> options){{#newline}}
    {{{#newline}}
        Options = options;{{#newline}}
    }{{#newline}}
{{#newline}}
    public {{contextName}} CreateDbContext(string[] args){{#newline}}
    {{{#newline}}
        return new {{contextName}}();{{#newline}}
    }{{#newline}}
{{#newline}}
    public {{contextName}} CreateDbContext(){{#newline}}
    {{{#newline}}
        return new {{contextName}}(Options);{{#newline}}
    }{{#newline}}
{{#newline}}
    public {{contextName}} CreateDbContext(DbContextOptions<{{contextName}}> options){{#newline}}
    {{{#newline}}
        return options == null{{#newline}}
            ? new {{contextName}}(){{#newline}}
            : new {{contextName}}(options);{{#newline}}
    }{{#newline}}
}";
}

This would result in the following generated code example:

    public class MyContextFactory : IDesignTimeDbContextFactory<MyContext>
    {
        private readonly DbContextOptions<MyContext> Options;

        public MyContextFactory()
        {
        }

        public MyContextFactory(DbContextOptions<MyContext> options)
        {
            Options = options;
        }

        public MyContext CreateDbContext(string[] args)
        {
            return new MyContext();
        }

        public MyContext CreateDbContext()
        {
            return new MyContext(Options);
        }

        public MyContext CreateDbContext(DbContextOptions<MyContext> options)
        {
            return options == null
                ? new MyContext()
                : new MyContext(options);
        }
    }

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions