要让EntityDataSource允许访问子实体,您需要执行以下步骤:
public class ParentEntity
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<ChildEntity> ChildEntities { get; set; }
}
public class ChildEntity
{
public int Id { get; set; }
public string Name { get; set; }
public ParentEntity ParentEntity { get; set; }
}
DbSet<>
属性为子实体类型添加一个新的DbSet
。public class MyDbContext : DbContext
{
public DbSet<ParentEntity> ParentEntities { get; set; }
public DbSet<ChildEntity> ChildEntities { get; set; }
// ...
}
OnModelCreating
方法配置子实体类型的关系。protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ParentEntity>()
.HasMany(pe => pe.ChildEntities)
.WithOne(ce => ce.ParentEntity)
.HasForeignKey(ce => ce.ParentEntityId);
}
Include
方法加载子实体。public async Task<IEnumerable<ParentEntity>> GetParentEntities()
{
return await _context.ParentEntities
.Include(pe => pe.ChildEntities)
.ToListAsync();
}
@foreach (var parentEntity in Model)
{
<div>
<h3>@parentEntity.Name</h3>
<ul>
@foreach (var childEntity in parentEntity.ChildEntities)
{
<li>@childEntity.Name</li>
}
</ul>
</div>
}
通过以上步骤,您可以成功地让EntityDataSource允许访问子实体。
领取专属 10元无门槛券
手把手带您无忧上云