我一直在玩 Entity Framework 一段时间了。但是由于某种原因,外键似乎都是空的,直到我明确地使用 Include 方法来包含它们。
根据我在这里读到的内容: Entity Framework 4.1 Virtual Properties 通过使它们成为虚拟它们应该是延迟加载的(而不是空的)。
这是我的模型:
class AltiGoalInfo
{
public int AltiGoalInfoId { get; set; }
public int ShotTime { get; set; } //Time it took from shooting till scoring
public virtual AltiPlayerInfo AltiPlayerInfo { get; set; }
public virtual AltiTeamEnum Team { get; set; }
public override string ToString()
{
double shotTime = ShotTime;
shotTime /= 1000;
shotTime = Math.Round(shotTime, 2);
return shotTime + " by " + AltiPlayerInfo;
}
}
class AltiPlayerInfo
{
public int AltiPlayerInfoId { get; set; }
public String VaporId { get; set; }
public String LastKnownNickname { get; set; }
public int LastKnownLevel { get; set; }
public int LastKnownAceRank { get; set; }
public Boolean LastKnownDemo { get; set; }
private IList<String> _knownIps = new List<String>();
public IList<String> KnownIps
{
get
{
return _knownIps;
}
set
{
_knownIps = value;
}
}
public string KnownIpsString
{
get
{
return String.Join(";", _knownIps);
}
set
{
_knownIps = value.Split(';').ToList();
}
}
public int Goals { get; set; }
public int MatchesPlayed { get; set; }
public int MatchesWon { get; set; }
public double CalcWinRate()
{
double mwon = MatchesWon;
double mplay = MatchesPlayed;
double result = mwon / mplay * 100.0;
return Math.Round(result, 0);
}
public DateTime FirstSeen { get; set; }
public DateTime LastSeen { get; set; }
public override string ToString()
{
return LastKnownNickname;
}
}
class AltiDbContext : DbContext
{
public DbSet<AltiPlayerInfo> AltiPlayerInfos { get; set; }
public DbSet<AltiGoalInfo> AltiGoalInfos { get; set; }
}
当我使用以下代码访问数据时,brrr 变量为空:
var test = altiDbContext.AltiGoalInfos.First();
var brrr = test.AltiPlayerInfo;
但是,当我首先手动包含时,它确实有效:
var test = altiDbContext.AltiGoalInfos.Include(t => t.AltiPlayerInfo).First();
var brrr = test.AltiPlayerInfo;
编辑:我还验证了 DbContext 的配置,默认情况下,配置中的所有设置都设置为 true(这应该启用延迟加载)。