Reputation: 18734
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.
Upvotes: 2
Views: 1248
Reputation: 11
If you are using EF v1, and you dont want to add the object as it is, you would need to do this.
u.TimezoneReference.EntityKey = new EntityKey("DB.TimeZone", "ID", id)
id is the foreign key.
If you are using EF v4 and still not getting the forgeign keys exposed then I guess you did not check the option to generate foreign keys while creating the model.
Upvotes: 1
Reputation: 34418
I think you have to fill in the timezone entity from the database, i.e.
u.timezone = DB.TimezoneSet.FirstOrDefault(tz => tz.Id == timezoneid);
assuming you've generated the set name with EF3; it'll be DB.Timezones
by 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 TimezoneReference
property is used to test whether child entities have been loaded, force them to load, etc.
Upvotes: 1
Reputation: 273784
I only have u.timezone
Yes, the model should expose a FK as a Navigation property. Just assign your TimeZone object there.
Upvotes: 1