0

我正在使用实体框架 4,SQLite 数据库和数据库优先方法。我已将我的表结构附加为快照。

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

在此处输入图像描述

“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();
}
4

1 回答 1

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);
于 2013-01-22T13:50:10.487 回答