ASP在获取数据库记录时不会加载所有实体
本文关键字:加载 实体 获取 数据库 记录 ASP | 更新日期: 2023-09-27 18:08:39
我在数据库中有一个类的记录:
public class Wallet
{
public Wallet()
{
}
public Wallet(string userName, CurrencySellPrices currencySellPrices, CurrencyAmounts currencyAmounts, double availableMoney)
{
UserName = userName;
CurrencySellPrices = currencySellPrices;
CurrencyAmounts = currencyAmounts;
AvailableMoney = availableMoney;
}
public int Id { get; set; }
public string UserName { get; set; }
public CurrencySellPrices CurrencySellPrices { get; set; }
public CurrencyAmounts CurrencyAmounts { get; set; }
public double AvailableMoney { get; set; }
}
,当我尝试用以下代码选择记录时:
public ActionResult Exchange()
{
var username = User.Identity.GetUserName();
var model = _db.Wallets.ToList().Find(r=>r.UserName==username);
return View(model);
}
它得到正确的记录,但是CurrenciesSellPrices和currencyamount类的对象是空的。在数据库中它们是正确的记录。
类是这样的:
{
public int Id { get; set; }
public int UsdAmount { get; set; }
public int EurAmount { get; set; }
public int ChfAmount { get; set; }
public int RubAmount { get; set; }
public int CzkAmount { get; set; }
public int GbpAmount { get; set; }
}
public class CurrencySellPrices
{
public int Id { get; set; }
public double UsdSellPrice { get; set; }
public double EurSellPrice { get; set; }
public double ChfSellPrice { get; set; }
public double RubSellPrice { get; set; }
public double CzkSellPrice { get; set; }
public double GbpSellPrice { get; set; }
}
我错过了一些东西在我的类,所以他们没有正确地从数据库加载?
如果没有明确指定,EntityFramework不会自动加载相关实体。
你可以使用Eager Loading达到预期的结果。
var model = _db.Wallets
.Include(wallet => wallet.CurrencySellPrices)
.Include(wallet => wallet.CurrencyAmounts)
.Find(r => r.UserName == username)
.ToList();
我还切换了Find和ToList的顺序,以便只提取选定的实体,而不是加载它们,然后过滤您需要的
你应该告诉实体框架加载它们,这是实体框架的流行行为,称为延迟加载"谷歌它"你的代码应该像这样
_db.Wallets.Include(w => w.CurrenciesSellPrices)
.Include(w => w.CurrencyAmounts)
.ToList().Find(r=>r.UserName==username);
你需要包含你的实体,试试这个:
_db.Wallets
.Include(nameof(Wallets.CurrencySellPrices))
.Include(nameof(Wallets.CurrencyAmounts))
.Find(r=>r.UserName==username)
.ToList();
_db.Wallets
.Include(wallet => wallet.CurrencySellPrices)
.Include(wallet => wallet.CurrencyAmounts)
.Find(r=>r.UserName==username)
.ToList();
前者通过名称包含属性,后者通过LINQ表达式包含属性。两者将给出相同的结果。
顾名思义,Include
在通过实体框架检索数据时包含关系。