【问题标题】:get the last inserted id and populate / insert into another table with that id获取最后插入的 id 并使用该 id 填充/插入到另一个表中
【发布时间】:2014-06-17 09:55:47
【问题描述】:

最后一个 id 结果返回 null,我如何获取最后插入的 id 并使用该 id 填充/插入到另一个表中

第二张表有两列主键和一列用于第一张表中的用户 ID。

[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
        {
          // ...
        }
    }
}

【问题讨论】:

  • 因为您当前模型的 UserId 为空?
  • 网络安全刚刚插入一行时,它怎么可能为空?除非我调用最后一个 id 的方式不正确?
  • 您的model 不知道,因为WebSecurity.CreateUserAndAccount 不会返回您刚刚创建的用户的ID。所以你的 model.UserId 永远不会设置

标签: c# entity-framework model-view-controller


【解决方案1】:

当你从 UI 获取 UserData 时

public ActionResult Register(RegisterModel model)

您的模型不会有用户 ID,但它会在您在数据库中插入记录时创建。所以你的 model.UserId 将为空。

你可以这样得到它:

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

你也可以使用 Max 函数来获取它:

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

但如果用户记录插入成功,您应该会得到结果。

【讨论】:

  • 现在我得到一个 {"Invalid object name 'dbo.Profile'."} .. 这是什么意思?
  • 请检查您的连接字符串。您的代码可能正在查找错误的数据库,请确保它正在调用正确的数据库而不是任何自动生成的数据库。
【解决方案2】:

这里的问题是您的 UserId 因此从未真正设置过

x.UserId == model.UserId

将始终返回空结果。

简单地“拉下最新的”通常不是一个好主意,因为您可能最终得到错误的 ID,例如如果有人在您查询数据库之前创建了一个新帐户怎么办?

一种更可靠的方法是使用您已有的信息来简单地请求新创建帐户的 ID

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

【讨论】:

  • 你是 rigt,如果多个用户正在使用该应用程序,那么这样做会更好
猜你喜欢
  • 1970-01-01
  • 2011-06-01
  • 2023-03-16
  • 2011-04-30
  • 2013-07-31
  • 1970-01-01
  • 1970-01-01
  • 2011-06-30
  • 2011-02-25
相关资源
最近更新 更多