我不确定类模型或RegisterIvestor.cs是否存在问题。我的Investor.cs属性均未保存并返回空值。
我正在尝试为不同类型的用户创建不同的登录名。我希望所有用户都保存到ApplicationUser。我发现下面的代码在构建和迁移时发现只是获取空数据。
ApplicationDBContext.cs
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserClaim<string>,
ApplicationUserRole, IdentityUserLogin<string>,
IdentityRoleClaim<string>, IdentityUserToken<string>>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<ApplicationUser>()
.HasOne(p => p.Investor)
.WithOne(b => b.ApplicationUser)
.HasForeignKey<Investor>(b => b.InvestorForeignKeyID);
}
public DbSet<ApplicationUser> ApplicationUser { get; set; }
public DbSet<Investor> Investor { get; set; }
}
RegisterInvestor.cshtml.cs
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser()
{
UserName = Input.Email,
Email = Input.Email,
FirstName = Input.FirstName,
LastName = Input.LastName,
Address = Input.Address,
City = Input.City,
State = Input.State,
Zip = Input.Zip
Investor = new Investor()
{
SsnTaxId = Input.SsnTaxId,
DOB = Input.DOB,
DriverClass = Input.DriverClass,
LicenseNumber = Input.LicenseNumber
}
};
}
}
ApplicationUser.cs
public class ApplicationUser : IdentityUser
{
public virtual Investor Investor { get; set; }
//other properties
}
Investor.cs
public class Investor : ApplicationUser
{
[Required]
[Display(Name = "SSN or TaxID")]
public string SsnTaxId { get; set; }
[Display(Name = "Date of Birth")]
public DateTime DOB { get; set; }
public string InvestorForeignKeyID { get; set; }
[ForeignKey("InvestorForeignKeyID")]
public virtual ApplicationUser ApplicationUser { get; set; }
}
显示数据
@Html.DisplayFor(m => Model.FirstName)
@Html.DisplayFor(m => m.Investor.SsnTaxId)
答案 0 :(得分:0)
首先,您不应该实例化具有相同名称的类,这是一种令人困惑且不明智的做法:
public virtual Investor UserInvestor { get; set; }
对于Invertor为null的情况,如果您在View中使用循环,则有可能由于您在ApplicationUser内部实例化对象而使它们全部为null,请尝试以下操作:
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
UserInvestor = new Investor();
if (ModelState.IsValid)
{
var user = new ApplicationUser()
{
UserName = Input.Email,
Email = Input.Email,
FirstName = Input.FirstName,
LastName = Input.LastName,
Address = Input.Address,
City = Input.City,
State = Input.State,
Zip = Input.Zip
UserInvestor.SsnTaxId = Input.SsnTaxId,
UserInvestor.DOB = Input.DOB,
UserInvestor.DriverClass = Input.DriverClass,
UserInvestor.LicenseNumber = Input.LicenseNumber
}
};
}
}
也可以在视图中显示名字,就像这样:
@Model.FirstName
或
@Html.DisplayFor(m => m.FirstName)