Reputation: 2215
I have a controller when I am getting a users credentials from AD and saving it into a Profiles
table. I also want to set some user preferences, however, in order to do this I need the Id
from Profile
I just saved to place it in the Preference
table.
var Profile = new Profile
{
//Id is auto increment
EmpId = viewmodel.EmployeeId;
//....
};
db.Profiles.Add(Profile);
db.SaveChanges();
Preferences Save:
var user = User.Identity.Name;
var getUser = (from gu in db.Profiles where user == gu.EmployeeId select gu.Id).Single();
var Preference = new Preference
{
UserId = getUser,
//...
};
db.Preferences.Add(Preference);
db.SaveChanges();
In this case, is this acceptable?
Upvotes: 1
Views: 716
Reputation: 4050
It looks like your variable getUser
(please rename this variable) ends up as the newly saved profile Id.. although you havent shown us where you define uc
.
anyway let me show you the magic of entity framework.
var profile = new Profile
{
//Id is auto increment
EmpId = viewmodel.EmployeeId;
//....
};
var preference = new Preference
{
//...
};
profile.Preferences.Add(preference;)
db.Profiles.Add(profile);
db.SaveChanges();
So as you can see you used more than 1 SaveChanges unnecessarily. There are times that you need to have more than one SaveChanges. like lets say you SaveChanges, post an id to an api, retrieve some values and save changes again. I never had to do that actually but i have had times that I need more than 1 save changes. For example I had to copy x amount of database records including x amount of related records into new records in a loop.
Upvotes: 1