views:

416

answers:

1

Hi,

Just using this as an example...

Here are the columns in my UserProfile table:
ProfileID (Primary key)
UserID (Foreign key)
Address
PhoneNumber

now, when I want to add a new user to the database using LINQ to Entities, here is what I'm doing:

UserProfile profileToAdd;
profileToAdd.ProfileID = 0;
profileToAdd.Address = "123 MyStreet";
profileToAdd.PhoneNumber = "123-4567";
/* How do I add in the UserID here? */

_myDB.AddToUserProfiles(profileToAdd);

A few questions...

  1. Is there anything special about dealing with Foreign keys that I need to know, or can I assign it just as I did with Address or PhoneNumber?

  2. The UserId is a Guid, and I need to retrieve it from the current user's UserId. I can't seem to get access to Membership class or User class (This is a C# Library so I'm guessing it needs a reference somehow, but my project is already referencing my Library so I can't reference back or I'll have a circular dependancy)

  3. I don't quite understand how to deal with Guids. When implementing getProfileByUserName(string userName), here's my problem...

first off I can't retrieve the UserID, here's what I tried:

Guid currUser = (Guid)from user in _ myDB.aspnet_Users
                             where user.UserName == userName
                             select new { user.UserId };

But it says I can't cast it to a Guid for some reason.

If you can provide any insight to any of these questions I would greatly appreciate it!

Thanks,
Matt

+1  A: 

If the database contains the proper constraints for the foreign key relationship, there should be a member in your UserProfile class, that points to a User object. The name might be a little weird, such as UserProfileUser or something like that.

However, you can change this name in the diagram. Just set a pointer to the user entity object and the framework will assign the correct id for you.

Timbo
So I don't even have to deal with the id, just the object itself?
Matt
Yes. The foreign key ID is just a link between two rows in two tables, and in C# this is so much better expressed as a object reference.
Timbo