First of all, let's define a few tables:
Users table will store information about a user:
Users
- UserID (int, PK)
- ...
UserTasks is a table that stores a task associated with a user:
UserTasks
- userID (int, FK to Users table)
- taskName (varchar)
When I generate the UserTasks table using the ADO Entity Framework, I'll get a class that looks like this:
UserTasks
- taskName (string)
- Users (collection of Users objects)
Note: There's no userID that is generated in the UserTasks table. So let's assume now that I need to insert a new user task... how do I do it? I don't have access to the userID FK field, so my only option is to do a lookup and populate a Users object, then pass that to my task object, like this:
//get the user we are interested in
var user = (from u in context.Users
where u.userID == 2
select u).FirstOrDefault();
//create the new task
UserTasks newTask = new UserTasks();
newTask.taskName = "New Task";
newTask.User = user;
The problem with the above is that I'm doing an extra and needless database call to populate my user object. Is there anyway to somehow create a new mapping to my userID field and still keep the User object?
Thanks
--Ryan