为什么我的所有外键都为空?

时间:2013-08-17 16:47:20

标签: c# sql-server database entity-framework entity-framework-5

我一直在玩Entity Framework一段时间了。但是出于某种原因,外键似乎都是null,直到我明确地使用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变量为null:

var test = altiDbContext.AltiGoalInfos.First();
var brrr = test.AltiPlayerInfo;

但是,当我首先手动包含时,它确实有效:

var test = altiDbContext.AltiGoalInfos.Include(t => t.AltiPlayerInfo).First();
var brrr = test.AltiPlayerInfo;

编辑: 我还验证了DbContext的配置,默认情况下,配置中的所有设置都设置为true(应该启用延迟加载)。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案,我不得不公开模型类