gpt4 book ai didi

c# - 如何在 UserProfile 中创建自定义附加字段

转载 作者:太空宇宙 更新时间:2023-11-03 10:43:29 25 4
gpt4 key购买 nike

我正在尝试创建自定义用户字段。我已经添加到注册表中。一切正常,自动创建表,但字段 CityNULL。有人知道为什么会这样吗?

public class ApplicationUser : IdentityUser
{
public string City { get; set; }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
static ApplicationDbContext()
{
Database.SetInitializer(new MySqlInitializer());
}
public ApplicationDbContext() : base("MySql.Data.MySqlClient")
{
}
}

MySqlInitializer.cs

public class MySqlInitializer : IDatabaseInitializer<ApplicationDbContext>
{
public void InitializeDatabase(ApplicationDbContext context)
{
if (!context.Database.Exists())
{
context.Database.Create();
}
else
{
var migrationHistoryTableExists = ((IObjectContextAdapter)context).ObjectContext.ExecuteStoreQuery<int>(
string.Format(
"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{0}' AND table_name = '__MigrationHistory'",
"[users]"));

if (migrationHistoryTableExists.FirstOrDefault() == 0)
{
context.Database.Delete();
context.Database.Create();
}
}
}
}

Register.cshtml

<div class="form-group">
@Html.LabelFor(m => m.City, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.City, new { @class = "form-control" })
</div>
</div>

AccountViewModels.cs公共(public)类 RegisterViewModel 添加

    [Required]
[Display(Name = "City")]
public string City { get; set; }

AccountController.cs

    [HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.UserName };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}

// If we got this far, something failed, redisplay form
return View(model);
}

null

最佳答案

创建用户对象时需要包含 City 变量:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.UserName, City = model.City };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}

// If we got this far, something failed, redisplay form
return View(model);
}

编辑:更新代码以使用您的代码。

关于c# - 如何在 UserProfile 中创建自定义附加字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24384851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com