实体框架创建数据库但不创建表

时间:2019-08-19 04:52:46

标签: entity-framework asp.net-core database-migration ef-migrations

运行迁移时,正在创建数据库,但是没有一个表。我不知道我在做什么错,因为前几天我做同样的事情没有问题。最初的迁移已运行并创建了数据库,但是没有一个表。我试过删除数据库和迁移,并再次进行整个过程,但是没有运气。下面是一些代码和我的文件夹结构的图片。希望有人可以指出我在做什么错。

这是我的模特之一:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Workout_Tracker.Models
{
public class Exercise
{
    public int ID { get; set; }

    public int Weight { get; set; }

    public string Name { get; set; }

    public int WorkoutID { get; set; }
    public Workout Workout { get; set; }

    public IList<ExerciseSet> Sets { get; set; }

}
   }

这是我的dbcontext:

namespace Workout_Tracker.Data
{
    public class ApplicationDbContext : DbContext
   {

    public DbSet<User> Users;

    public DbSet<Workout> Workouts;

    public DbSet<Exercise> Exercises;

    public DbSet<ExerciseSet> Exercise_Sets;
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {

    }
}
}

这里是迁移:

namespace Workout_Tracker.Migrations
{
    public partial class first : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {

    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {

    }
}
}

这是startup.cs:

namespace Workout_Tracker

{
    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.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

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


        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseAuthentication();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

}

这是我的文件夹结构:

enter image description here

1 个答案:

答案 0 :(得分:2)

您只是暴露了DbSet<T>,而没有使用getter和setter方法。

将数据库集更改为此:

public DbSet<User> Users { get; set; }

public DbSet<Workout> Workouts { get; set; }

public DbSet<Exercise> Exercises { get; set; }

甚至更好的是,使用fluent-API,并且完全不公开DbSet<T>

   protected override void OnModelCreating(ModelBuilder builder)
   {
      // you can define table names, keys and indices here
      // there is also `IEntityTypeConfiguration<T>` which is much better since it keeps the DbContext clean
      // https://codeburst.io/ientitytypeconfiguration-t-in-entityframework-core-3fe7abc5ee7a
      builder.Entity<User>();
      builder.Entity<Workout>();
      builder.Entity<Exercise>();
   }

然后,在注入ApplicationDbContext时,可以使用通用方法context.Set<T>。例如context.Set<User>来检索用户数据库集。

仅供参考:ExerciseSet目前没有数据库集,Exerciseprivate static StringBuilder StringBuilderResult; private static boolean DetectRaspBPi() { GetInfoByExecuteCommandLinux("cat /proc/device-tree/model", false); return StringBuilderResult.toString().toLowerCase().contains("raspberry"); } private static void GetInfoByExecuteCommandLinux(String command, boolean getList){ try { Process pb = new ProcessBuilder("bash", "-c", command).start(); BufferedReader reader=new BufferedReader( new InputStreamReader(pb.getInputStream()) ); String line; if (getList){ ListStringBuilderResult = new ArrayList<>(); } else { StringBuilderResult = new StringBuilder(); while((line = reader.readLine()) != null) { if (getList){ ListStringBuilderResult.add(line); } else { StringBuilderResult.append(line); } } } catch (Exception e){ System.out.println(e.getMessage()); } } 的子集。

用于实体框架的docs非常好,我建议您熟悉它们。

相关问题