如果EF的导航属性有默认值,则不会被加载。

问题描述 投票:0回答:0

我有一个 Transaction 在代码优先的方法中,带导航属性的类。Account.

public class Transaction 
{
    [Key]
    public int Id { get; set; }
    public int AccountId { get; set; }
    public virtual Account Account { get; set; }
    public Transaction() 
    {
        // Account = new Account(GlobalValues.AppData.DefaultAccount); // this causes the problem!!!
    }
}

如果在默认的 Transaction Account 未设置,则

var toDisplay = db.Transactions.Take(10).ToList(); 

读作 Account 适当。如果 Account 在默认的构造函数中被设置,那么似乎是 Account 没有被读取,但使用了构造函数中设置的值。我试过急切加载,但没有用。

var toDisplay3 = db.Transactions.Take(10).Include(e => e.Account).ToList();

我目前的解决方法是只设置 AccountId 但它在其他地方造成了问题。

c# entity-framework eager-loading navigation-properties
© www.soinside.com 2019 - 2024. All rights reserved.