获取数据库记录时,ASP不会加载所有实体

时间:2016-09-25 20:57:36

标签: c# asp.net asp.net-mvc-4

我在班级数据库中有记录:

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和CurrencyAmounts类的对象为空。在数据库中,它们是适当的记录。

类看起来像这样:

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

我的课程中是否遗漏了某些内容,因此无法从数据库中正确加载?

3 个答案:

答案 0 :(得分:0)

如果没有明确告知,EntityFramework不会自动加载相关实体。

您可以使用Eager Loading获得预期的结果。

var model = _db.Wallets
                .Include(wallet => wallet.CurrencySellPrices)
                .Include(wallet => wallet.CurrencyAmounts)
                .Find(r => r.UserName == username)
                .ToList();

我还会切换查找 ToList 的顺序,以便仅提取所选实体,而不是全部加载它们,然后过滤所需的实体。

答案 1 :(得分:0)

你应该告诉实体框架加载它们,它是实体框架的流行行为,称为延迟加载“google it” 你的代码看起来应该是这样的

_db.Wallets.Include(w => w.CurrenciesSellPrices)
            .Include(w => w.CurrencyAmounts)
            .ToList().Find(r=>r.UserName==username);

答案 2 :(得分:0)

您需要包含您的实体,请尝试以下操作:

_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包括通过Entity Framework检索数据时的关系。