ASP.NET MVC Inserting object and related object into 2 tables
- by ile
I have two tables: Users and UserOwners. Table UserOwners contains list of users that certain user created (list of child-users) - or to be more precise, it contains UserOwnerID and UserID fields.
So, now I want to create a new user... in Controller I have something like this:
var userOwner = accountRepository.GetUser(User.Identity.Name);
var userOwnerID = userOwner.UserID;
UserReference userReference = new UserReference();
userReference.UserOwnerID = userOwnerID;
if (ModelState.IsValid)
{
try
{
//accountRepository.Add(user);
//accountRepository.Save();
return View();
}
catch
{
return View();
}
}
What is the easiest way to add new user to a table Users and matching UserOwner to UserOwners table.
Is it suppose to be something like this?
public void Add(User user)
{
db.Users.InsertOnSubmit(user);
db.UserReferences.InsertOnSubmit(user.UserReference);
}
...or I will have to pass two objects and after adding user I must read it's ID and than assign it to userReference object and add that object to DB?
If so, how to read ID of the last object added?
Thanks,
Ile