簡體   English   中英

在 Entity Framework Core 中包含子屬性

[英]Include Child Property in Entity Framework Core

我在 .NET 核心和實體框架核心工作。

我有以下 model 類

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; }
}

在我的FD controller 中,我試圖訪問銀行和分行的屬性。

   public IActionResult Index()
    {
        ICollection<FD> fixedDeposits = _unitOfWork.FD.GetAll(includeProperties: "Branch,Bank").ToList();
        return View(fixedDeposits);
    }

但是遇到錯誤

System.InvalidOperationException:“為警告“Microsoft.EntityFrameworkCore.Query.InvalidIncludePathError”生成錯誤:無法找到在基於字符串的包含路徑“Bank”中指定的導航“Bank”。 通過將事件 ID 'CoreEventId.InvalidIncludePathError' 傳遞給 'DbContext.OnConfiguring' 或 'AddDbContext' 中的 'ConfigureWarnings' 方法,可以抑制或記錄此異常。

也嘗試過配置我的數據庫上下文,但沒有成功。

optionsBuilder
          .UseLazyLoadingProxies()
          .ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.InvalidIncludePathError))
          .UseSqlServer();

Repo 中的 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();
    }

問題似乎是您正在嘗試包含 2 層深的“銀行”。

以下應該有效:

public IActionResult Index()
{
    ICollection<FD> fixedDeposits = _unitOfWork.FD.GetAll(includeProperties: "Branch,Branch.Bank").ToList();
    return View(fixedDeposits);
}

EF Core 還具有類型安全的“ThenInclude”構造,盡管它可能不適合您的情況。

query.Include(fd => fd.Branch)
    .ThenInclude(b => b.Bank);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM