【问题标题】:No tables generated using code-first in .NET Core在 .NET Core 中没有使用代码优先生成的表
【发布时间】:2022-02-15 01:56:14
【问题描述】:

我正在使用 VS 2016、SQL Server 2016、.NET Core、代码优先,当我尝试更新数据库时,没有生成表。

语境:

public DataContext()
{
}

public DataContext(DbContextOptions<DataContext> options)
            : base(options)
{
}
                
public virtual DbSet<Relative> Relatives { get; set; }
public virtual DbSet<User> Users { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        optionsBuilder.UseSqlServer(\"Server=DESKTOP-ARVMMP2\\\\SQLEXPRESS;Database=PraxedesDb;Trusted_Connection=True\");
    }
 }

 protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
     modelBuilder.HasAnnotation(\"Relational:Collation\", \"SQL_Latin1_General_CP1_CI_AS\");

     modelBuilder.Entity<Relative>(entity =>
            {
                entity.ToTable(\"Relatives\");

                entity.Property(e => e.Id)
                    .ValueGeneratedNever()
                    .HasColumnName(\"Id\");

                entity.Property(e => e.DateOfBirth).HasColumnType(\"DateOfBirth\");
                entity.Property(e => e.RelativeNames).HasColumnName(\"RelativeNames\");
                entity.Property(e => e.RelativeLastNames).HasColumnName(\"RelativeLastNames\");                
                entity.Property(e => e.RelativeGender).HasColumnName(\"RelativeGender\");
                entity.Property(e => e.RelativeDocumentNumber).HasColumnName(\"RelativeDocumentNumber\");
                entity.Property(e => e.InLaw).HasColumnName(\"InLaw\");
                entity.Property(e => e.RelativeAge).HasColumnName(\"RelativeAge\");

                entity.Property(e => e.UserId).HasColumnName(\"UserId\");

                entity.HasOne(d => d.User)
                    .WithMany(p => p.Relatives)
                    .HasForeignKey(d => d.UserId)
                    .HasConstraintName(\"UserId\");
            });

    modelBuilder.Entity<User>(entity =>
            {
                entity.ToTable(\"Users\");

                entity.Property(e => e.Id)
                    .ValueGeneratedNever()
                    .HasColumnName(\"Id\");

                entity.Property(e => e.DateOfBirth).HasColumnType(\"DateOfBirth\");
                entity.Property(e => e.UserNames).HasColumnName(\"UserNames\");
                entity.Property(e => e.UserLastNames).HasColumnName(\"UserLastNames\");
                entity.Property(e => e.UserPlatformName).HasColumnName(\"UserPlatformName\");
                entity.Property(e => e.UserPassword).HasColumnName(\"UserPassword\");
                entity.Property(e => e.UserGender).HasColumnName(\"UserGender\");
                entity.Property(e => e.UserDocumentNumber).HasColumnName(\"UserDocumentNumber\");                               
            });

    OnModelCreatingPartial(modelBuilder);
}

partial void OnModelCreatingPartial(ModelBuilder modelBuilder);

型号:

        public User()
        {
            Relatives = new HashSet<Relative>();
        }

        public int Id { get; set; }
        public DateTime? DateOfBirth { get; set; }
        public string UserNames { get; set; }
        public string UserLastNames { get; set; }
        public string UserPlatformName { get; set; }
        public string UserPassword { get; set; }
        public string UserGender { get; set; }
        public int UserDocumentNumber { get; set; }

        public virtual ICollection<Relative> Relatives { get; set; }

    public class Relative
    {
        public int Id { get; set; }
        public DateTime? DateOfBirth { get; set; }
        public string RelativeNames { get; set; }
        public string RelativeLastNames { get; set; }        
        public string RelativeGender { get; set; }
        public int RelativeDocumentNumber { get; set; }
        public string InLaw { get; set; }
        public int RelativeAge { get; set; }

        public int? UserId { get; set; }
        public virtual User User { get; set; }
    }

启动:

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)
{
    // for reference loop handling 
    services.AddControllers().AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });

    // for mySettingModel
    services.Configure<MySettingsModel>(Configuration.GetSection(\"MySettings\"));

    // for Cors Allow
    services.AddCors();

    services.AddControllers();
    // services.AddDbContext<DataContext>(options => options.UseSqlServer(Configuration.GetConnectionString(\"ConnectionString\")));
    services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc(\"v1\", new OpenApiInfo { Title = \"PraxedesBackend\", Version = \"v1\" });
            });
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // for Cors Allow
    app.UseCors(options => options.WithOrigins(\"http://localhost:4200\")
                .AllowAnyMethod()
                .AllowAnyHeader()
            );

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint(\"/swagger/v1/swagger.json\", \"PraxedesBackend v1\"));
    }

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
}

一个用户有很多亲戚,即两个模型之间的关系。

DataContext 有问题吗?或者模型?你能帮我么?

我试过:

 modelBuilder.Entity<Relative>()
            .HasOne<User>(s => s.User)
            .WithMany(g => g.Relatives)
            .HasForeignKey(s => s.UserId);

也没有结果。

我做了迁移和更新数据库命令

    标签: c# .net-core ef-code-first


    【解决方案1】:

    创建类和 dbcontext 来创建数据库和表是不够的。 您必须运行两个命令:

    dotnet ef migrations add "create db and tables"
    
    dotnet ef database update
    

    每次更改模型时,都必须运行这 2 个命令以反映对数据库的更改...

    【讨论】:

    • 对不起,我忘了说我是这样做的
    猜你喜欢
    • 2019-03-23
    • 2014-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    相关资源
    最近更新 更多