假设我有一个全新的应用程序,应该使用CodeFirst迁移,其中列出了Buildings
的{{1}}。
我做一个ASP.NET Core API应用程序以列出Cities
的{{1}}的建筑物...
我的模特:
Disctricts
我应该在Cities
中保留什么以启用我的第一个EF迁移?
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; }
}
如果我仅保留建筑物,则不会创建其他两个表,这里的建议是什么?
我需要显示建筑物,但是在BuildingsContext
中是否需要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; }
}
的集合?
还是足以获得Building
,然后通过“深度加载”我们可以恢复Context
和Citi
s?
反之亦然,我只需要District
s,然后我就可以通过引用Building
s和Building
es从下到上恢复健康?
答案 0 :(得分:1)
我应该在BuildingsContext中保留什么,以启用我的第一个EF 迁移吗?
您需要在OnModelCreating
内配置模型。例如,
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");
});
}
}
然后,您将DbContext注册到startup.cs
内的DI容器中。
public class Startup
{
...
public void ConfigureServices(IServiceCollection services)
{
...
services.AddDbContext<BuildingsContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
...
}
...
}
最后,您可以在PowerShell or Console中的任何一个内部运行迁移命令。例如,在PowerShell内部。
Add-Migration InitialCreate
Update-Database