entity framework: how to assign foreign key in a entity
Here is my tables structure..
Profile: ProfileID (PK), ProfileName varchar(50), GenderID (Fk)
Gender: GenderID (PK), GenderName varchar(50)
Gender table has 2 possible values : Male, Female.
In entity framework, when I am updating the profile with GenderID, I use the following code:
profile.GenderID = Repository.
GetGender(
Request.Form["Profile.GenderName"].ToString()
).GenderID;
Repository.Save();
GetGender method looks like the following:
public Gender Get开发者_开发技巧Gender(string genderName)
{
return (from gender in db.Genders
where (gender.GenderName.Equals(genderName))
select gender).First();
}
Is there a better way of doing it? I feel like I am not using Entity Framework like it should be...
If I assign the value to profile.Gender.GenderID as opposed to profile.GenderID then I am updating the original Gender Lookup table which is not what I want.
I am confused..
Thanks..
If the only thing you have to look up the gender is the text description, then that's the best you're going to do (although I would probably add StringComparison.OrdinalIgnoreCase
to the Equals
). If you have the PK, there are other options.
It seems like a lot of effort to keep calling the database for this information. Could you not retrieve the pairs of values once, for example in Application_Start
, put it in Cache
, and then reference it as needed? After all, the values are not likely to change very often.
精彩评论