.net 在迁移环境中保留什么?
假设我有一个全新的应用程序,应该使用CodeFirst迁移,它列出了.net 在迁移环境中保留什么?,.net,entity-framework,asp.net-core,entity-framework-core,entity-framework-migrations,.net,Entity Framework,Asp.net Core,Entity Framework Core,Entity Framework Migrations,假设我有一个全新的应用程序,应该使用CodeFirst迁移,它列出了城市的建筑 我使用ASP.NET核心API应用程序列出城市的地区的建筑 我的模型: public class City { public int CityId { get; set; } public string Name { get; set; } List<District> Districts { get; set; } } public class District { pu
城市的建筑
我使用ASP.NET核心API应用程序列出城市的地区的建筑
我的模型:
public class City
{
public int CityId { get; set; }
public string Name { get; set; }
List<District> Districts { get; set; }
}
public class District
{
public int DistrictId { get; set; }
public string Name { get; set; }
public int CityId { get; set; }
List<Building> Buildings { get; set; }
}
public class Building
{
public int DistrictId { get; set; }
public int BuildingId { get; set; }
public string Name { get; set; }
}
如果我只保留建筑物,它不会创建其他两个表,这里的建议是什么
我需要显示建筑物,但是否需要在上下文中收集建筑物
或者只需要获得花旗银行的es,然后通过“深度加载”我们就可以恢复地区和大楼
或者,维切维萨,我只需要大楼
s,然后我就可以通过参考地区
s和花旗
es从下到上休养了
我应该在BuildingContext中保留什么来启用我的第一个EF
迁移
public class BuildingsContext : DbContext
{
// should I use these two?
// public DbSet<City> Cities { get; set; }
// public DbSet<District> Districts { get; set; }
public DbSet<Building> Buildings { get; set; }
}
您需要在模型创建中配置模型。比如说,
public partial class BuildingsContext : DbContext
{
public BuildingsContext()
{
}
public BuildingsContext(DbContextOptions<BuildingsContext> options)
: base(options)
{
}
public virtual DbSet<Building> Building { get; set; }
public virtual DbSet<City> City { get; set; }
public virtual DbSet<District> District { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Building>(entity =>
{
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(50);
entity.HasOne(d => d.District)
.WithMany(p => p.Building)
.HasForeignKey(d => d.DistrictId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Building_District");
});
modelBuilder.Entity<City>(entity =>
{
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(50);
});
modelBuilder.Entity<District>(entity =>
{
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(50);
entity.HasOne(d => d.City)
.WithMany(p => p.District)
.HasForeignKey(d => d.CityId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_District_City");
});
}
}
最后,在中的任意一个中运行迁移命令。例如,在PowerShell内部
Add-Migration InitialCreate
Update-Database
上下文是实体框架的核心,而不是迁移。您将需要访问的表放在那里。然后,迁移会将这些数据与上一次迁移(如果有)进行比较并进行更改。第一次迁移应该生成所有内容。你遇到了什么?如果我不向上下文添加任何内容,迁移将是空的,那么如果我应该手动执行,那么自动迁移的意义何在?@SteveGreene如果我查看win的答案,我可以认为上下文是迁移的真正核心,因为有定义的地方。另外,如果我有任何上下文,First Add Migration将创建并使用它,因此它与迁移不可分割,甚至定义它们。是的,迁移使用上下文。是对版本6迁移的说明。大部分还是一样的。EF会拉入相关的表格,但我更喜欢显式的,就像Win的答案一样。所以,没有什么自动的,我应该做的只是手工?因为,如果我在上下文中添加一组建筑、城市和地区,它似乎会在第一次迁移时自动构建一些东西。另一点是,我应该列出建筑
s,但事实上,我只需要恢复花旗
s,然后我就可以恢复地区
s和建筑
s。。。为什么在代码显示的上下文中需要列表
s?
Add-Migration InitialCreate
Update-Database