【发布时间】:2021-09-23 06:33:51
【问题描述】:
我在使用新的 ASP.NET Core 应用程序(代码优先)注册新用户时遇到问题。
注册时,我使用的是继承自 `IdentityUser` 的 `ApplicationUser`。
public class ApplicationUser : IdentityUser
{
[Required]
[DefaultValue(5)]
public int ViewerRange { get; set; }
[DefaultValue(false)]
[Required]
public bool IsTACAccepted { get; set; }
public DateTime? TACAccepted { get; set; }
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public DateTime Created { get; set; }
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime Modified { get; set; }
public string Role { get; set; }
public ApplicationUser()
{
Modified = DateTime.Now;
Created = DateTime.Now;
}
}
这是 Register.cshtml.cs 的一部分
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl ??= Url.Content("~/");
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
UserName = Input.Email,
Email = Input.Email,
Role = Input.Role,
Created = DateTime.Now,
Modified = DateTime.Now,
IsTACAccepted = false,
ViewerRange = 5
};
var result = await _userManager.CreateAsync(user, Input.Password);
//[...]
注册时,CreateAsync 方法失败并出现以下错误:
InvalidOperationException: The value for property 'ApplicationUser.Modified' cannot be set to null because its type is 'System.DateTime' which is not a nullable type.
我不明白为什么会失败。
谁能详细解释一下?
亲切的问候
【问题讨论】:
-
您将
Modified标记为DatabaseGeneratedOption.Computed,这意味着它的值应该被忽略,但您需要设置一个显式值。也没有迹象表明该值将如何生成 - 触发器?默认约束?这不是唯一的怪事。DatabaseGeneratedOption.IdentityCreated没有意义。自动递增值仅适用于数字字段 -
你想做什么做?你想如何处理这些列?是否要指定显式值?他们应该获得默认值吗?在那里面。如果您需要添加例如默认约束和/或触发器来填充这些列。
-
如果您想自己指定值,请删除
DatabaseGenerated属性并将它们用作普通字段。您可以通过指定默认属性值来避免显式分配,例如public DateTime Created { get; set; } = DateTime.Now。这不会在数据库中生成DEFAULT约束或触发器
标签: asp.net-core asp.net-identity