LINQ to SQL:SubmitChanges()不起作用?

时间:2010-08-09 14:52:57

标签: c# database linq linq-to-sql

这是我的代码

var bt = new BachtuocvnDataContext();
        var matchedTeams = (from lt in bt.Bet_Leagues_Teams
                         where lt.LeagueID == leagueID
                         select (lt)).Single();
        matchedTeams.TeamID = teamID;
        bt.SubmitChanges(ConflictMode.ContinueOnConflict);

它不会更新表格。传统查询效果很好,我在这里找到了类似的问题:

LINQ not updating on .SubmitChanges()

但我查了一下,发现Bet_Leagues_Teams确实有一个主键。

Bet_Leagues_Teams课程:

int ID (primary key)
int LeagueID;
int TeamID;
啊,啊,我可怕的错误。我忘记了Bet_Leagues_Teams可能不包含所需的记录。我必须检查记录是否存在,然后更新它,否则它不存在,我必须将它添加到表中。对我感到羞耻。原谅我浪费你的时间。谢谢。

3 个答案:

答案 0 :(得分:1)

using(BachtuocvnDataContext bt = new BachtuocvnDataContext() ) 
{ 
    Bet_Leagues_Teams matchedTeam = 
        bt.Bet_Leagues_Teams.Where(lt => lt.LeagueID == leagueID)
        .SingleOrDefault(); 

    if(matchedTeam != null)
    {
        matchedTeam.TeamID = teamID; 
        bt.SubmitChanges(ConflictMode.ContinueOnClonflict); 
    }
} 

答案 1 :(得分:0)

using( var bt = new BachtuocvnDataContext() )
{
    var matchedTeam = bt.Bet_Leagues_Teams.Single( lt => lt.LeagueID == leagueID );
    matchedTeam.TeamID = teamID;
    bt.SubmitChanges( ConflictMode.ContinueOnClonflict );
}

答案 2 :(得分:0)

请注意,如果有多个匹配元素,Single()将抛出异常(如果您的schemea正确地模拟了“联盟”的概念,那么会有)

您可能希望在那里使用First()