在ASP.NET Core 6.0中,可以通过继承现有模型来创建子模型。下面是一个示例代码,展示如何在Person模型中创建Address子模型:
首先创建一个 AddressModel:
public class AddressModel
{
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
}
然后,通过继承PersonModel并添加AddressModel属性来创建PersonModel的子模型:
public class PersonModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public AddressModel Address { get; set; }
}
现在,可以使用PersonModel及其子模型 AddressModel来创建数据库表:
public class MyDbContext : DbContext
{
public DbSet Persons { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity(entity =>
{
entity.ToTable("Persons");
entity.HasKey(e => e.Id);
entity.Property(e => e.FirstName)
.IsRequired()
.HasMaxLength(50);
entity.Property(e => e.LastName)
.IsRequired()
.HasMaxLength(50);
entity.OwnsOne(e => e.Address, a =>
{
a.Property(p => p.Street)
.IsRequired()
.HasMaxLength(100);
a.Property(p => p.City)
.IsRequired()
.HasMaxLength(50);
a.Property(p => p.State)
.IsRequired()
.HasMaxLength(50);
a.Property(p => p.ZipCode)
.IsRequired()
.HasMaxLength(10);
});
});
}
}
在上面的代码示例中,CreateTable中的OwnsOne函数说明了如何将AddressModel作为一个OwnedEntity的字段添加到Person表中。
现在,你可以使用以下代码初始化数据库并添加一个Person到数据库中:
using (var context = new MyDbContext())
{
context