Scenario
I have tables like
(ID, Email, Password)
(ID, UserID_FK, First, Last, Created_On, Created_By_FK)
This is how I create new user account
Users us = new Users
{
Email = 'xyz@example.com',
Password = 123
};
User_Profile up = new User_Profile
{
First = 'Kamalpreet',
Last = 'Singh',
Created_On = DateTime.Now
};
us.User_Profile.Add(up);
Context x = new Context();
x.Users.Add(us);
db.Save();
Above code creates following records in database-
Users Table-
ID = 100
Email = xyz@example.com
Password = 123
User_Profile Table-
ID = 1
UserID_FK = 100
First = Kamalpreet
Last = Singh
Created_On = 2016-08-06 10:40:10.000
Created_By_FK = NULL
Question
In User_Profile table, why the Users(ID)
gets copied to only User_Profile(UserID_FK)
table and not get copied to User_Profile(Created_By_FK)
Both UserID_FK and Created_By_FK columns are Foreign Key references to Users(ID) table.
When you are generating a database first DbContext, you get two collections to add against (if you have two relationships setup - one for each key). For example, you should then see:
You would then add the profile to both collections to have both foreign keys updated properly when persisting. Entity Framework keeps track of the fact you have added the same object reference to two collections, and will save it properly.
Note: The other option is to save the user, and then put the ID you get back on both foreign key properties, but this may be less efficient.