简体   繁体   中英

get the last inserted id and populate / insert into another table with that id

The last id result is returning null, how do I get the last inserted id and populate / insert into another table with that id

The 2nd table has two columns primary key and a column for the userid from the first table.

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
    UsersContext db = new UsersContext();
    if (ModelState.IsValid)
    {
        // Attempt to register the user
        try
        {
            WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Email = model.Email }, false);
            WebSecurity.Login(model.UserName, model.Password);

            UserProfile obj = db.UserProfiles.Last(x => x.UserId == model.UserId);                    
            db.Profiles.Add(new Profile { UserID = obj });
            db.SaveChanges();
        }
        catch
        {
          // ...
        }
    }
}

When you are getting UserData from UI

public ActionResult Register(RegisterModel model)

your model will not have Id of user, but it will be created when you insert record in database. So your model.UserId would be null.

You can get it like this :

UserProfile lastUser = db.UserProfiles.OrderByDescending(x => x.UserId).FirstOrDefault();                  
            db.Profiles.Add(new Profile { UserID = lastUser.UserId });
            db.SaveChanges();

You can also get it using Max function :

var lastUserId = db.UserProfiles.Max(u => u.UserId);

but you should get result if user record inserted suscessfully.

The issue here is your UserId is never actually set therefore

x.UserId == model.UserId

will always return an empty result.

It's generally not a great idea to simply " pull down the latest " because you could potentially end up with the wrong ID eg what if someone creates a new account just before you query the DB?

A more robust approach is to simply request the ID of the newly created account using the information already available to you

var newUserId = WebSecurity.GetUserId(model.UserName);
var profile = db.UserProfiles.SingleOrDefault(x => x.UserId == newUserId);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM