I am battling to work out how to handle foriegn keys with Entity Framework, when editing or adding a new record. For example, I have a person table, which has a timezone_id linking to my timezone table.
But the model seems to not include timezone_id. I see it’s a new way of doing things, but … how do I store my record?
My method:
public static string CreateUser(string username, string email, string password, string firstname, string surname, int timezoneId)
{
user u = new user();
u.surname = surname;
u.firstname = firstname;
u.email = email;
u.password = password;
u.username = username;
Db.AddTousers(u);
Db.SaveChanges();
return username;
}
I can’t do u.timezone_id = timezoneid;
I only have u.timezone (which seems to be the actual entity), and u.timezoneReference, which I am not sure what to do with.
I think you have to fill in the timezone entity from the database, i.e.
assuming you’ve generated the set name with EF3; it’ll be
DB.Timezonesby default in EF4. If this is EF4 then you can also regenerate your EDMX for that table with ID columns included too – there’s an option on the front page of the wizard.The
TimezoneReferenceproperty is used to test whether child entities have been loaded, force them to load, etc.