2

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.

1
  • 1
    When talking about EF, the version(s) are rather important. Commented Jan 3, 2011 at 9:54

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

I only have u.timezone

Yes, the model should expose a FK as a Navigation property. Just assign your TimeZone object there.

2 Comments

Thanks Henk - could you assist with that? How would I assign it? I thought I could do u.timezone_id = timezoneid; - but I can't. How do I assign a timezone object? My dropdown list only has a description and and id... So, I am passing the Id into the method (int).
You can use the Id to look up the TimeZone (from the context) or change the listbox to hold complete TimeZones.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.