【发布时间】: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