0

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.

Community
  • 1
  • 1
Delta76
  • 13,931
  • 30
  • 95
  • 128
  • 2
    So what's the primary key of Bet_League_Teams? Also, why are you setting `matchedTeams.ID` to itself? – Jon Skeet Aug 09 '10 at 14:59
  • @Jon: I edited my question, added more details and fixed some typos. – Delta76 Aug 09 '10 at 15:03
  • out of interest, can you confirm if the matchedTeams instance contains a primary key value? ie. the ID property has a value? What are the two values of matchedTeams.TeamID (after the data has been retrieved) and the value of teamID? – Pure.Krome Aug 09 '10 at 15:10

3 Answers3

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); 
    }
} 
Andy Evans
  • 6,997
  • 18
  • 72
  • 118
0
using( var bt = new BachtuocvnDataContext() )
{
    var matchedTeam = bt.Bet_Leagues_Teams.Single( lt => lt.LeagueID == leagueID );
    matchedTeam.TeamID = teamID;
    bt.SubmitChanges( ConflictMode.ContinueOnClonflict );
}
Jerod Houghtelling
  • 4,783
  • 1
  • 22
  • 30
0

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.

James Curran
  • 101,701
  • 37
  • 181
  • 258