C# 在实体框架核心中包含子属性
我在.NET核心和实体框架核心工作 我有以下的模型课C# 在实体框架核心中包含子属性,c#,entity-framework-core,C#,Entity Framework Core,我在.NET核心和实体框架核心工作 我有以下的模型课 public class FD { public virtual Branch Branch { get; set; } public int Id { get; set; } public int BranchId { get; set; } } public class Branch { public Branch() { FD= new HashSet<FD>(); }
public class FD
{
public virtual Branch Branch { get; set; }
public int Id { get; set; }
public int BranchId { get; set; }
}
public class Branch
{
public Branch()
{
FD= new HashSet<FD>();
}
public virtual ICollection<FixedDeposit> FixedDeposits { get; set; }
public virtual Bank Bank { get; set; }
}
public class Bank
{
public Bank()
{
Branches = new HashSet<Branch>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Branch> Branches { get; set; }
}
回购中的GetAll实现如下
public IEnumerable<T> GetAll(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, string includeProperties = null)
{
IQueryable<T> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
if (includeProperties != null)
{
foreach (var includeProp in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProp);
}
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
return query.ToList();
}
public IEnumerable GetAll(表达式筛选器=null,Func orderBy=null,字符串includeProperties=null)
{
IQueryable query=dbSet;
if(过滤器!=null)
{
query=query.Where(过滤器);
}
if(includeProperties!=null)
{
foreach(includeProperties.Split中的var includeProp(新字符[]{',},StringSplitOptions.RemoveEmptyEntries))
{
query=query.Include(includeProp);
}
}
if(orderBy!=null)
{
returnorderby(query.ToList();
}
返回query.ToList();
}
问题似乎是您试图包含“Bank”,它有两层深度
以下方面应起作用:
public IActionResult Index()
{
ICollection<FD> fixedDeposits = _unitOfWork.FD.GetAll(includeProperties: "Branch,Branch.Bank").ToList();
return View(fixedDeposits);
}
用GetAll代码更新了我的问题。。我们不能为这个问题提供一些通用的解决方案吗???@Bombo答案更新。看看它是否有效,这对我的案子很有效。
public IEnumerable<T> GetAll(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, string includeProperties = null)
{
IQueryable<T> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
if (includeProperties != null)
{
foreach (var includeProp in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProp);
}
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
return query.ToList();
}
public IActionResult Index()
{
ICollection<FD> fixedDeposits = _unitOfWork.FD.GetAll(includeProperties: "Branch,Branch.Bank").ToList();
return View(fixedDeposits);
}
query.Include(fd => fd.Branch)
.ThenInclude(b => b.Bank);