C# EF在向注册表添加新属性后未插入数据库
我在asp.net MVC默认代码中的C# EF在向注册表添加新属性后未插入数据库,c#,asp.net,entity-framework,C#,Asp.net,Entity Framework,我在asp.net MVC默认代码中的RegisterViewModel类中添加了两个新字段。验证有效,但新添加字段的值不会插入到数据库中,而是插入其他字段。该页未返回任何错误 我猜我需要在AccountController类中做一些事情,在这里附近的某个地方: var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateA
RegisterViewModel
类中添加了两个新字段。验证有效,但新添加字段的值不会插入到数据库中,而是插入其他字段。该页未返回任何错误
我猜我需要在AccountController
类中做一些事情,在这里附近的某个地方:
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
不知道到底是怎么回事
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
//await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
TempData["Email"] = user.Email;
return RedirectToAction("Confirm", "Account");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
公共异步任务);
TempData[“Email”]=user.Email;
返回重定向操作(“确认”、“账户”);
}
加法器(结果);
}
//如果我们走到这一步,有些东西失败了,重新显示形式
返回视图(模型);
}
如果需要向数据库添加新字段,则需要添加以修改模型
应用程序用户
而不是视图模型注册服务模型
。
因此,在您的问题中,您需要向RegisterViewModel
模型添加新字段,但实际上您需要更新ApplicationUser
类,因为RegisterViewModel
仅用于UI。例如,要添加新字段PersonId
,您需要修改ApplicationUser
模型并迁移您的数据库硒
public class ApplicationUser : IdentityUser
{
public string PersonId { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
您没有在
ApplicationUser
实例中分配新属性,假设您在model类中添加了一个“PhoneNumber”属性,那么您必须将其值复制到用户,如下所示
var user = new ApplicationUser { UserName = model.Email, Email = model.Email,PhoneNumber=model.PhoneNumber };
您可以共享代码。您确定正在对您的上下文对象调用
SaveChanges
吗?我在AccountController
@Dai中没有SaveChanges
。只有我刚才添加的字段不会插入到数据库中。其他字段也会被插入。@hello可能是因为您在viewmodel中而不是在entity中添加了。
var user = new ApplicationUser { UserName = model.Email, Email = model.Email,PhoneNumber=model.PhoneNumber };