我有一门描述人的课程:
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
我还有两个类继承了这个
Person
类,并且每个类都只有一个不同的属性。
我将创建一个迁移,并且必须为这些类中的属性设置一些属性,但我不需要将 Person
类添加到数据库中。我该怎么办?
我可以在
Person
类中设置属性,继承它但在迁移中传递它吗?
我希望这能满足您的需求!如果您不想在数据库中使用
Person
类,只需将其从 DbContext 中删除即可。如果您发现自己需要调整每个子类的配置,理想的解决方案是使用 IEntityTypeConfiguration
。我在下面提供了一个示例来帮助您。
定义具有公共属性的基类“Person”。
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
创建一个继承自“Person”的派生类“ChildPerson1”。 向此类添加特定属性“FavoriteToy”。
public class ChildPerson1 : Person
{
public string? FavoriteToy { get; set; }
}
创建另一个继承自“Person”的派生类“ChildPerson2”。 向此类添加特定属性“姓氏”。
public class ChildPerson2 : Person
{
public string Surname { get; set; }
}
定义继承自DbContext的数据库上下文'PersonDbContext'。 包括每个派生类的 DbSet 属性。 使用“OnModelCreating”方法应用配置。
public class PersonDbContext : DbContext
{
public PersonDbContext(DbContextOptions<PersonDbContext> options)
: base(options)
{
}
public DbSet<ChildPerson1> ChildPerson1s => Set<ChildPerson1>();
public DbSet<ChilPerson2> ChilPerson2s => Set<ChilPerson2>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.ApplyConfigurationsFromAssembly(typeof(PersonDbContext).Assembly);
}
}
定义实现“IEntityTypeConfiguration”的配置类“ChildPerson1Configurations”。 为“ChildPerson1”实体配置特定属性。
public class ChildPerson1Configurations :
IEntityTypeConfiguration<ChildPerson1>
{
public void Configure(EntityTypeBuilder<ChildPerson1> builder)
{
// Additional configurations specific to ChildPerson1.
// For example, set the maximum length for the 'FavoriteToy' property.
builder.Property(p => p.FavoriteToy).HasMaxLength(50);
// Change the column name for the 'FirstName' property.
builder.Property(p => p.FirstName).HasColumnName("First_Name");
}
}
如果需要,添加 ChildPerson2Configurations。