【问题标题】:Add "same" Entity to multiple Entities results in null将“相同”实体添加到多个实体导致 null
【发布时间】:2014-09-09 13:37:00
【问题描述】:

抱歉标题不好,我会在这里尝试更好地解释。为简单起见,假设我的 Code First 迁移中有两个实体。一名球员有一个身份和一个名字,一场比赛有一个身份,一个赢家和一个松散的人。赢家和输家是玩家(不是同一个玩家)。我想要的是一场比赛可以有一个赢家和一个输家。我有以下 DbContext:

public IDbSet<Player> Players { get; set; }
public IDbSet<Match> PlayerMatches { get; set; }

我的 Player 类如下所示:

public int PlayerId { get; set; }
public string Name { get; set; }
public virtual ICollection<Match> Matches { get; set; }

我的比赛班级:

public int MatchId { get; set; }
public Player Winner { get; set; }
public Player Looser { get; set; }

如果我的解析中有以下代码,(解析为“正确”的正确数据放入Db):

Player player1 = db.Players.Where(....); //Here I just select which is the correct player (OK)
Player player2 = db.Players.Where(....);
Match m = new Match();
m.Winner = player1;
m.Looser = player2;

player1.Matches.Add(m);
player2.Matches.Add(m);
db.SaveChanges();

如果我在将匹配添加到两个玩家之前检查匹配,一切正常,并且添加没有任何错误。当我检查 Db 或尝试检索匹配时,问题就出现了。根据我“使用”的玩家,根据“我的玩家”是否赢/输,赢家/输家为空。如果这个玩家赢了,反之亦然……我相信我错过了一些映射,但我不明白是哪个,我对 Code First 很陌生,这是我遇到的第一个 db 问题应用。

有什么想法吗?

Ciao!

【问题讨论】:

  • 抱歉占用了任何人的时间,我错过了 Match 类中 Looser 和 Winner 属性之前的“virtual”关键字......现在工作正常。漫长的一天...

标签: c# database entity-framework ef-code-first entity-framework-migrations


【解决方案1】:

如果其他人度过了漫长的一天并发现自己面临类似问题,请将“虚拟”添加到案例所需的属性中。在我的情况下,比赛类中的获胜者和失败者。

【讨论】:

    猜你喜欢
    • 2019-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多