简体   繁体   中英

LINQ to SQL: SubmitChanges() does not work?

Here's my code

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);

It does not update the table. Traditional query works well, I found a similar question here:

LINQ not updating on .SubmitChanges()

but I checked and found that Bet_Leagues_Teams does have a primary key.

Bet_Leagues_Teams class:

int ID (primary key)
int LeagueID;
int TeamID;

Ahhhh, MY TERRIBLE MISTAKE. I forgot that Bet_Leagues_Teams may not contains the record needed. I must check if the record existed, and then update it, or it does not exist and I must add it to the table. Shame on me. Forgive me for wasting your time. Thank you.

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); 
    }
} 
using( var bt = new BachtuocvnDataContext() )
{
    var matchedTeam = bt.Bet_Leagues_Teams.Single( lt => lt.LeagueID == leagueID );
    matchedTeam.TeamID = teamID;
    bt.SubmitChanges( ConflictMode.ContinueOnClonflict );
}

Note that Single() will throw an exception if there is more than one matching elements (which, if your schemea models the concept of "league" properly, there will be)

You may want to use First() there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM