Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto migration in EF Core in three tier application

i have three tier application in Asp.net Mvc Core and use EF core, now i want create auto migration ,

i have DAL layer that my context available here

 public class AdminContext : DbContext
    {

    public AdminContext(DbContextOptions<AdminContext> options) : base(options)
    {

    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<AdsAdsCategory>()
             .HasKey(bc => new { bc.AdsId, bc.AdsCategoryId });

        modelBuilder.Entity<AdsAdsCategory>()
            .HasOne(bc => bc.Ads)
            .WithMany(b => b.AdsAdsCategories)
            .HasForeignKey(bc => bc.AdsId);

        modelBuilder.Entity<AdsAdsCategory>()
            .HasOne(bc => bc.Category)
            .WithMany(c => c.AdsAdsCategories)
            .HasForeignKey(bc => bc.AdsCategoryId);
    }

    public DbSet<Ads> Adses { get; set; }
    public DbSet<AdsCategory> AdsCategories { get; set; }
    public DbSet<AdsPosition> AdsPositions { get; set; }
    public DbSet<AdsCustomer> AdsCustomers { get; set; }
}

and in my application startup

i write this code

var context = app.ApplicationServices.GetService<AdminContext>();

       if (!context.Database.EnsureCreated())
            context.Database.Migrate();

when i run application database was created and table generate but __migrationhistory doesn't exist and migration not generate,

when in start up i remove this line code

 if (!context.Database.EnsureCreated())

database was created and __migrationhistory table generated,but my model table not generate,

how i can solve this problem ? and run auto migration in EF Core in three tier application?

like image 565
MrMVC Avatar asked Jan 05 '23 09:01

MrMVC


2 Answers

You need to do the following to enable Migration in MVC .NET Core.

1-open the Package Manager Console in Visual Studio. Type and execute this code.

add-migration ClassName

pm> add-migration FirstInitialize

2-After executing the code, the migration classes will be created for your models

 public partial class FirstInitialize : Migration
 {
    protected override void Up(MigrationBuilder migrationBuilder)
   {
  //After executing the code, this section will be automatically   generated for your models 
   }

}

3-Then, with the following code you enter in the class section of the program.cs main method, your models will be built into a database.

using (var scope = host.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
        try
        {
            var context = services.GetRequiredService<YouDbContext>();
            context.Database.Migrate();
        }
        catch (Exception ex)
        {
            var logger = services.GetRequiredService<ILogger<Program>>();
            logger.LogError(ex, "An error occurred while seeding the atabase.");
        }
    }

4-Each time you change your models or add a new one, you have to repeat the steps. Choose a new name for your migration every time. Sample:

pm> add-migration SecondInitialize

*I can't speak english well

like image 141
abolfazl mousavi Avatar answered Jan 13 '23 01:01

abolfazl mousavi


Automatic migration like in EF6 do not exist in EF core. You either have to generate your migrations before starting and then use

context.Database.Migrate();

or you drop your whole database on each launch and use

context.Database.EnsureCreated();

to recreate the updated database. The second one wont allow you to add any migrations later on, so you have to recreate entire database each time. To delete database you can use

context.Database.EnsureDeleted();
like image 42
Mats391 Avatar answered Jan 13 '23 01:01

Mats391