How do you configure the DbContext when creating Migrations in Entity Framework Core?

后端 未结 7 1287
时光取名叫无心
时光取名叫无心 2020-12-11 02:51

Is there way that dependency injection can be configured/bootstrapped when using Entity Framework\'s migration commands?

Entity Framework Core supports dependency in

7条回答
  •  独厮守ぢ
    2020-12-11 03:20

    Use IDesignTimeDbContextFactory

    If a class implementing this interface is found in either the same project as the derived DbContext or in the application's startup project, the tools bypass the other ways of creating the DbContext and use the design-time factory instead.

    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Design;
    using Microsoft.EntityFrameworkCore.Infrastructure;
    
    namespace MyProject
    {
        public class BloggingContextFactory : IDesignTimeDbContextFactory
        {
            public BloggingContext CreateDbContext(string[] args)
            {
                var optionsBuilder = new DbContextOptionsBuilder();
                optionsBuilder.UseSqlite("Data Source=blog.db");
    
                return new BloggingContext(optionsBuilder.Options);
            }
        }
    }
    

    applied in Entity Framework 2.0, 2.1


    Using IDbContextFactory is now obsolete.

    Implement this interface to enable design-time services for context types that do not have a public default constructor. Design-time services will automatically discover implementations of this interface that are in the same assembly as the derived context.

    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Infrastructure;
    
    namespace MyProject
    {
        public class BloggingContextFactory : IDbContextFactory
        {
            public BloggingContext Create()
            {
                var optionsBuilder = new DbContextOptionsBuilder();
                optionsBuilder.UseSqlServer("connection_string");
    
                return new BloggingContext(optionsBuilder.Options);
            }
        }
    }
    

    more info : https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext

    If you're not happy with the hard-coded connection-string, take a look at this article.

提交回复
热议问题