Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Create Database correctly

$
0
0

Hello,

i used in my App (Core 2.0) for local testing mslocaldb and on server i used a MS SQL Database.

In my Core 1.1 Solution i create and migrate the Database by code. 

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            [...]
            DBInitialization.Initialize(app);
            DBInitialization.Seed(app);
            [...]
        }


        public static void Initialize(this IApplicationBuilder app)
        {
            try
            {
                ApplicationDbContext context = (ApplicationDbContext)app.ApplicationServices.GetService(typeof(ApplicationDbContext));

                if (!context.Database.EnsureCreated())
                    context.Database.Migrate();
            }
            catch (Exception e)
            {

                throw e;
            }
        }

I used the same code in my 2.0 app. I get an error

"Cannot resolve scoped service 'Portal.Data.ApplicationDbContext' from root provider."

So i used a simple class to initilze and seed my Database. 

services.AddTransient<DataService>();

public void Configure 
{
[...]
seeder.SeedAsync().Wait();
}
public class DataService
    {
        internal readonly ApplicationDbContext DBContext;
        internal readonly UserManager<Models.Entities.AppUser> UserManager;
        internal readonly RoleManager<IdentityRole> RoleManager;
        internal readonly IHttpContextAccessor HttpContext;
        internal readonly Get GetData;
        internal readonly IOptions<ViewModels.AppSettings> AppSettings;

        public DataService(ApplicationDbContext ctx,
            UserManager<Models.Entities.AppUser> userManager,
            IHttpContextAccessor httpContext,
            IServiceProvider serviceProvider,
            IOptions<ViewModels.AppSettings> appSettings)
        {
            DBContext = ctx;
            this.UserManager = userManager;
            this.HttpContext = httpContext;
            this.GetData = new Get(this);
            this.AppSettings = appSettings;
            RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
        }

        public async Task SeedAsync()
        {

            DBContext.Database.EnsureCreated();


            await CreateAppUsersAsync();
            await CreateRolesAsync();
            await AddRolesToUserAsync();
            await CreateDeptorsAsync();
            await AddDeptorsToUserAsync();
        }
[...] }

Now my Database is createt, but there is no __EFMigrationsHistory. So i can't use use database-update. The Datatabase.Migrate() command does nothing change. 

Where is my Error?


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>