gpt4 book ai didi

c# - 在 Entity Framework Core 中包含子属性

转载 作者:行者123 更新时间:2023-12-05 04:55:13 30 4
gpt4 key购买 nike

我在 .NET Core 和 Entity Framework Core 工作。

我有以下模型类

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: 'An error was generated for warning 'Microsoft.EntityFrameworkCore.Query.InvalidIncludePathError': Unable to find navigation 'Bank' specified in string based include path 'Bank'. This exception can be suppressed or logged by passing event ID 'CoreEventId.InvalidIncludePathError' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.'

也尝试配置我的数据库上下文,但没有成功。

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 层深的“Bank”。

以下应该有效:

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

关于c# - 在 Entity Framework Core 中包含子属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65511167/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com