views:

320

answers:

1

Hi,

I have two 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 appropriatly.

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;
    }
+1  A: 

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;
Henk Holterman
so can you give me an example?
Tony
thanks for the new acronym: POCO: Plain Old CLR Object! Hehe didn't know that!
Tony
I was thinking: Plain Old C# Object, but maybe CLR is better.
Henk Holterman
Still not working :(
Tony
Show the new code, show the association properties and define 'not working'
Henk Holterman
@Tony: it's just 1 line {-:
Henk Holterman
@Henk: Thanks! That works, as it changes the reference to the child object, but the changes do not get persisted to the database when calling SaveChanges on it. Any ideas?
Tony
Checking entitystate of newteam and profiledata after changing FK references, they are both in 'unchanged' state, so why would that be?
Tony
Check the mapping of your FKs, in my simple test the changes _did_ get saved.
Henk Holterman