I have t开发者_如何学Cwo tables Team_DATA and Driver_PROFILE_DATA in an SQL database. For every driver_profile there can be many teams.
So there's a one-to-many relation on the driver_profile to team_data table. I want to update a team_data foreign key reference in the Driver_profile table of an already existing record to another team_data record that already exists.
I want to do this using entity framework. Here what I want: having a list of teams to select from, finding the record in the team_data table and updating it's FK in the driver_profile appropriately.
So in the code below, the passed parameter is the newly selected team out of the team_data table.
Now I need it to update it FK reference in the Driver_profile table.
Here's what I've got:
UPDATE: Code Updated. It does not save it to database, even if I call savechanges. No errors.
public Driver_PROFILE_DATA GetSelectedTeam(string team)
{
ObjectQuery<Team_DATA> td = raceCtxt.Team_DATA;
ObjectQuery<Driver_PROFILE_DATA> drpr = raceCtxt.Driver_PROFILE_DATA;
var selteam = from t in td where t.Team_Name == team select t;
Team_DATA newteam = new Team_DATA();
newteam = selteam.Select(x => x).First();
// get driver_profile with associated team_data
var data = from a in raceCtxt.Driver_PROFILE_DATA.Include("Team_DATA") select a;
// put it in driver_profile entity
profileData = data.Select(x => x).First();
profileData.Team_DATAReference.Attach(newteam);
return profileData;
}
Entity Framework should give you a nice Association between the two classes, Update the references as you would using POCOs and stay away from the ID values.
Something like:
newTeam.Profile.Teams.Remove(profileData); // separate from old Profile
profileData.Teams.Add(newTeam);
EDIT:
I made a little test, it is sufficient to set the reference to the Parent object:
newTeam.Profile = profileData;
精彩评论