VeryVicious VeryVicious - 2 months ago 12
ASP.NET (C#) Question

ASP doesn't load all entities when getting a database record

I have a record in database of a class:

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

}


and when I try to pick a record with this code:

public ActionResult Exchange()
{
var username = User.Identity.GetUserName();
var model = _db.Wallets.ToList().Find(r=>r.UserName==username);
return View(model);
}


It gets the right record, but objects of classes CurrenciesSellPrices and CurrencyAmounts are null. In the database they are proper records.

Classes look like this:

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


Am I missing something im my classes so they aren't properly loaded from the database?

Answer

EntityFramework doesn't load related entities automatically if it's not explicitly told.

You can achieve the expected result with Eager Loading.

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

I've also switch the order of Find and ToList in order to extract only the chosen entity and not to load them all and then filter the one you need.