【发布时间】:2018-06-17 16:46:28
【问题描述】:
我正在使用 EF Core 2.1,并且我的域中有这些类。
public class HomeSection2
{
public HomeSection2()
{
HomeSection2Detail = new List<HomeSection2Detail>();
}
public Guid ID { get; set; }
public string Title { get; set; }
public string Header { get; set; }
public List<HomeSection2Detail> HomeSection2Detail { get; set; }
}
public class HomeSection2Detail
{
public Guid ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Link { get; set; }
public int? Sequence { get; set; }
public HomeSection2 HomeSection2 { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.RemovePluralizingTableNameConvention();
//HomeSection2
modelBuilder.Entity<HomeSection2>().HasKey(s => s.ID);
modelBuilder.Entity<HomeSection2>().Property(s => s.ID).ValueGeneratedOnAdd();
modelBuilder.Entity<HomeSection2>().Property(s => s.Title).IsRequired();
modelBuilder.Entity<HomeSection2>().Property(s => s.Header).IsRequired();
//HomeSection2Detail
modelBuilder.Entity<HomeSection2Detail>()
.HasOne(p => p.HomeSection2)
.WithMany(b => b.HomeSection2Detail);
modelBuilder.Entity<HomeSection2Detail>().HasKey(s => s.ID);
modelBuilder.Entity<HomeSection2Detail>().Property(s => s.ID).ValueGeneratedOnAdd();
modelBuilder.Entity<HomeSection2Detail>().Property(s => s.Title).IsRequired();
modelBuilder.Entity<HomeSection2Detail>().Property(s => s.Sequence).IsRequired();
}
我有一个通用的回购
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
protected readonly DbContext Context;
public Repository(DbContext context)
{
Context = context;
}
public IEnumerable<TEntity> GetAll()
{
return Context.Set<TEntity>().ToList();
}
}
当我像这样从应用程序var obj = _uow.HomeSection2s.GetAll() 调用GetAll 时,它不会填充详细信息。
【问题讨论】:
-
所以使用
Include。 -
考虑使用 .ToList() 返回 IQueryable 而不是 IEnumerable。通过使用 IQueryable,您的消费者可以决定如何处理实体,包括执行 .Include()、选择数据子集、进行计数、使用 .Any() 进行检查等。或者,您需要将参数传递给您的方法来指示您想要包含哪些扩展属性,然后在每个的 repo 方法中添加 .Include()。
标签: c# entity-framework asp.net-core asp.net-core-mvc