Entity Framework: working with FK (why are they hiding?)

First of all, define a few tables:

The users table stores information about the user:

Users
- UserID (int, PK)
- ...

      

UserTasks is a table that stores the task associated with the user:

UserTasks
- userID (int, FK to Users table)
- taskName (varchar)

      

When I create a UserTasks table using ADO Entity Framework, I get a class that looks like this:

UserTasks
- taskName (string)
- Users (collection of Users objects)

Note. There is no user ID in the UserTasks table. So let's assume I need to insert a new custom task ... how do I do this? I don't have access to the userID FID field, so my only option is to search and populate the Users object and then pass it to my task object, like so:

//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 am making an additional and unnecessary database call to populate my custom object. Do I need to somehow create a new mapping in the userID field and store the User object?

thank

- Ryan

0


source to share


1 answer


Not now, but possibly in the next version .



+1


source







All Articles