ASP.NET MVC Inserting object and related object into 2 tables
Posted
by ile
on Stack Overflow
See other posts from Stack Overflow
or by ile
Published on 2010-05-12T12:50:18Z
Indexed on
2010/05/12
12:54 UTC
Read the original article
Hit count: 190
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
© Stack Overflow or respective owner