多对多对另一对多对多对单个实体
问题描述:
对于使用实体框架的多对多关系,我有一个相当简单的问题。多对多对另一对多对多对单个实体
情况是这样的我有3种型号SectionName:
public class SectionName : BaseEntity
{
public SectionName()
{
SectionsSuffix = new List<SectionSuffix>();
}
[Required]
public string Name { get; set; }
public ICollection<SectionSuffix> SectionsSuffix { get; set; }
}
科后缀:
[Table("SectionsSuffix")]
public class SectionSuffix : BaseEntity
{
public SectionSuffix()
{
SectionLines = new List<SectionLine>();
SectionsName = new List<SectionName>();
}
[Required]
public string Name { get; set; }
public ICollection<SectionLine> SectionLines { get; set; }
public ICollection<SectionName> SectionsName { get; set; }
}
而且SectionLines:
[Table("SectionLines")]
public class SectionLine : BaseEntity
{
public SectionLine()
{
SectionsSuffix = new List<SectionSuffix>();
}
[Required]
public string Name { get; set; }
public ICollection<SectionSuffix> SectionsSuffix { get; set; }
}
现在SectionsName是由许多与许多人SectionsSuffix和许多到SectionLines在上下文中使用FluentApi相关和接线表:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SectionName>()
.HasMany(suffix => suffix.SectionsSuffix)
.WithMany(name => name.SectionsName)
.Map(nameSuffix =>
{
nameSuffix.ToTable("SectionsNameSuffix");
nameSuffix.MapLeftKey("SectionNameId");
nameSuffix.MapRightKey("SectionSuffixId");
});
modelBuilder.Entity<SectionSuffix>()
.HasMany(line => line.SectionLines)
.WithMany(suffix => suffix.SectionsSuffix)
.Map(nameSuffix =>
{
nameSuffix.ToTable("SectionsSuffixLines");
nameSuffix.MapLeftKey("SectionSuffixId");
nameSuffix.MapRightKey("SectionLinesId");
});
}
现在,如果有当我打电话SectionsNames没问题,我可以得到SectionsSuffix名单,我想这一个电话让还SectionNames名单猛吃具体SectionSuffix,这可能吗?
现在使用存储库模式的过程是这样的:
IList<SectionName> sections = SectionRepository.GetAll(x => x.SectionsSuffix).ToList();
public virtual IEnumerable<T> GetAll(params Expression<Func<T, object>>[] includes)
{
IQueryable query = includes.Aggregate(_dbSet.AsQueryable(), (current, include) => current.Include(include));
return (IEnumerable<T>) query;
}
答
回答是相当简单的,我会需要使用:
IList<SectionName> sections = SectionRepository.GetAll(name => name.SectionsSuffix,
name => name.SectionsSuffix.Select(suffix => suffix.SectionLines)).ToList();
public virtual IEnumerable<T> GetAll(params Expression<Func<T, object>>[] includes)
{
IQueryable query = includes.Aggregate(_dbSet.AsQueryable(), (current, include) => current.Include(include));
return (IEnumerable<T>) query;
}
答
如果我想查询某事。像你想要做的那样,它会是这样的:
using System;
using System.Data.Entity;
public class SectionRepository
{
private readonly _context;
public SectionRepository(IMyDbContext context)
{
_context = context
}
public ICollection<SectionName> GetAll()
{
return _context.SectionNames
.Include(sn => sn.SectionsSuffix.SectionLine)
.Select(sn => sn).ToList();
}
}
请试试看,上面的代码没有经过测试。