向具有2个外键的表中添加行时出错

时间:2013-01-22 13:44:12

标签: c# visual-studio-2010 entity-framework sqlite

我正在使用Entity框架4,SQLite数据库采用数据库第一种方法。我已将表结构附加为快照。

我能够在Bnb_Company和Bnb_Player表中写入/读取数据,但是当我尝试在Bnb_Game表中输入一行时,我收到以下错误。

enter image description here

'MockStockDbEntities.Bnb_Game'中的实体参与'Bnb_CompanyBnb_Game'关系。找到0个相关的'Bnb_Company'。 1'Bnb_Company'是预期的。!

//Reset company values
if (context.Bnb_Company.Count() > 0)
{
    var companydetails = context.Bnb_Company.ToList();
    foreach (var company in companydetails)
    {
        company.ESC = 0;
        company.MarketValue = company.FaceValue;
    }
    context.SaveChanges();
}

if (context.Bnb_Player.Count() > 0)
{
    var playerDetails = context.Bnb_Player.ToList();
    //Reset Player values
    foreach (var player in playerDetails)
    {
        player.NetAmount = 0;
        player.Amount = 1000;
        if (context.Bnb_Company.Count() > 0)
        {
            var companyDetails = context.Bnb_Company.ToList();
            foreach (var company in companydetails)
            {
                if (context.Bnb_Game.Count() > 0 && (context.Bnb_Game.Where(b => b.PlayerId == player.Id && b.CompanyId == company.Id).Count() > 0))
                {
                    var specificCompanyShare = context.Bnb_Game.Where(b => b.PlayerId == player.Id && b.CompanyId == company.Id).FirstOrDefault();
                    specificCompanyShare.Shares = company.DefaultShares;
                }
                else
                {
                    Bnb_Game playerCompanyShare = new Bnb_Game();
                    playerCompanyShare.CompanyId = company.Id;
                    playerCompanyShare.PlayerId = player.Id;
                    playerCompanyShare.Shares = company.DefaultShares;
                    context.Bnb_Game.AddObject(playerCompanyShare);
                }
            }
        }

    }
    context.SaveChanges();
}

1 个答案:

答案 0 :(得分:1)

尝试使用实体引用而不是Id值。

 Bnb_Game playerCompanyShare = new Bnb_Game();
 playerCompanyShare.Bnb_Company = company;
 playerCompanyShare.Bnb_Player = player;
 playerCompanyShare.Shares = company.DefaultShares;
 context.Bnb_Game.AddObject(playerCompanyShare);