C#: asp. net CORE empty Миграция - PullRequest
       48

C#: asp. net CORE empty Миграция

0 голосов
/ 20 февраля 2020

Я пытаюсь добавить миграцию из DatabaseContext, но когда я добавляю миграцию, я генерирую ее пустой, как это. Я следовал этому уроку

namespace MovieExampleAppDotNetCore.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class ModelMigration : DbMigration
    {
        public override void Up()
        {
        }

        public override void Down()
        {
        }
    }
}

Это модели, Конфигурация миграции, Запуск и DatabaseContext

Movie.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace MovieExampleAppDotNetCore.Models
{
    public class Movie
    {   
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int MovieId { get; set; }
        public String Name { get; set; }

        [Column(TypeName = "datetime2")]
        public DateTime? DateCreated { get; set; }
    }
}

Customer.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace MovieExampleAppDotNetCore.Models
{
    public class Customer
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int CustomerId { get; set; }
        public string Name { get; set; }
        public string LastName { get; set; }
        public bool IsCreated { get; set; }
        public int MaxMovies { get; set; }

        [Column(TypeName = "datetime2")]
        public DateTime Created { get; set; }

        [Column(TypeName = "datetime2")]
        public DateTime? LastEdited { get; set; }


    }
}

Configuration.cs

namespace MovieExampleAppDotNetCore.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<MovieExampleApp.Persistention.DatabaseContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
        }

        protected override void Seed(MovieExampleApp.Persistention.DatabaseContext context)
        {

        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method
        //  to avoid creating duplicate seed data.
    }
}

}

DatabaseContext.cs

using Microsoft.EntityFrameworkCore;
using MovieExampleAppDotNetCore.Models;
using System.Data.Entity;


namespace MovieExampleApp.Persistention
{
    public class DatabaseContext : System.Data.Entity.DbContext
    {
        public DatabaseContext() : base("main")
        {
            //Database.Initialize(true);
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }

        public Microsoft.EntityFrameworkCore.DbSet<Movie> Movies { get; set; }
        public Microsoft.EntityFrameworkCore.DbSet<Customer> Customers { get; set; }
    }
}

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using MovieExampleApp.Persistention;
using System.Linq;

namespace MovieExampleAppDotNetCore
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddDbContext<DatabaseContext>(
                        options => options.UseSqlServer(Configuration.GetConnectionString("DatabaseContext")));

            services.AddControllersWithViews().AddNewtonsoftJson();

            services.AddControllersWithViews(options =>
            {
                options.InputFormatters.Insert(0, GetJsonPatchInputFormatter());
            });

        }

        private static NewtonsoftJsonPatchInputFormatter GetJsonPatchInputFormatter()
        {
            var builder = new ServiceCollection()
                .AddLogging()
                .AddMvc()
                .AddNewtonsoftJson()
                .Services.BuildServiceProvider();

            return builder
                .GetRequiredService<IOptions<MvcOptions>>()
                .Value
                .InputFormatters
                .OfType<NewtonsoftJsonPatchInputFormatter>()
                .First();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Я надеюсь, что кто-то может сказать, что я делаю неправильно.

Ответы [ 3 ]

0 голосов
/ 20 февраля 2020

Насколько я знаю, вам не нужно использовать [DatabaseGenerated(DatabaseGeneratedOption.Identity)], поскольку вы используете [Key] - этого достаточно, чтобы задать первичный ключ для свойства.

Попробуйте сделать так:

Сначала я бы удалил пустую миграцию, набрав в Package-Manger-Console:

Remove-Migration

Я также предположил, что у вас нет других миграций там, где у вас есть фактически добавили эти модели, которые вы хотите добавить сейчас.

затем:

ApplicationDbContext Class:

public class ApplicationDbContext : DbContext
{
            public ApplicationDbContext(DbContextOptions<ApplicationDbContext> context) : base(context)
    {
    }

    public DbSet<Movie> Movies { get; set; }
    public DbSet<Customer> Customers { get; set; }
}

Я предполагаю, что у вас есть все в вашем запуске, чтобы обновить базу данных, но только для того, чтобы упоминание:

Startup:

    public void ConfigureServices(IServiceCollection services)
    {

     //some code...
            services.AddDbContext<ApplicationDbContext>(
            options => options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));
    }

И, конечно, обновите строку подключения в настройках приложения. json, чтобы отразить имя подключения:

  "ConnectionStrings": {
"DevConnection": "Server=SERVER; Database=DB; Trusted_Connection=True; MultipleActiveResultSets=True;",

 }

Затем введите Консоль управления пакетами: add-migration [Migration Name]

0 голосов
/ 21 февраля 2020

Я нашел ответ на мою проблему. Я использовал using System.Data.Entity; вместо using Microsoft.EntityFrameworkCore;

Вот рабочий код

DatabaseContext.cs

using Microsoft.EntityFrameworkCore;
using MovieExampleAppDotNetCore.Models;


namespace MovieExampleApp.Persistention
{
    public class DatabaseContext : DbContext
    {
        public DatabaseContext(DbContextOptions<DatabaseContext> context) : base(context)
        {
            //Database.Initialize(true);
        }

        public DatabaseContext()
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }

        public DbSet<Movie> Movies { get; set; }
        public DbSet<Customer> Customers { get; set; }
    }
}

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Microsoft.EntityFrameworkCore.SqlServer;
using System.Linq;
using MovieExampleApp.Persistention;

namespace MovieExampleAppDotNetCore
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }


        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddDbContext<DatabaseContext>(
            options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));


            services.AddControllersWithViews().AddNewtonsoftJson();

            services.AddControllersWithViews(options =>
            {
                options.InputFormatters.Insert(0, GetJsonPatchInputFormatter());
            });

        }

        private static NewtonsoftJsonPatchInputFormatter GetJsonPatchInputFormatter()
        {
            var builder = new ServiceCollection()
                .AddLogging()
                .AddMvc()
                .AddNewtonsoftJson()
                .Services.BuildServiceProvider();

            return builder
                .GetRequiredService<IOptions<MvcOptions>>()
                .Value
                .InputFormatters
                .OfType<NewtonsoftJsonPatchInputFormatter>()
                .First();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
0 голосов
/ 20 февраля 2020

используйте это; добавить миграцию миграции1 перед вызовом update-database

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...