我正在使用Entity Framework Core。我正在创建大量对象(即用户),并将这些用户添加到我的数据库中。
步骤如下:
List<User>
_context.Users.AddRange(usersList)
_context.SaveChanges()
这是代码:
User currentUser = currentUserToValidate.ToModel<User>();
currentUser.Tenant = tenant;
currentUser.CreatedOn = DateTime.UtcNow;
currentUser.LastLogOn = DateTime.MinValue;
currentUser.LastLogOnAttempt = DateTime.MinValue;
currentUser.SecurityStamp = NewSecurityStamp();
if (string.IsNullOrEmpty(currentUserToValidate.Password))
{
currentUserToValidate.Password = PasswordGenerator.Generate(tenant.PasswordPolicy.MinimumPasswordLength);
}
string aesPassword = AESHelper.EncryptString(currentUserToValidate.Password);
currentUser.AESPassword = aesPassword;
if (string.IsNullOrEmpty(currentUser.UserName))
{
currentUser.UserName = currentUser.Email;
}
var hPwd = new PasswordHasher<User>().HashPassword(currentUser, currentUserToValidate.Password);
currentUser.PasswordHash = hPwd;
concurrentAddValidUsers(validUsers, currentUser);
然后
public async Task CreateBatch(List<User> usersToAdd, List<PasswordHistory> passwordHistories)
{
try
{
int number = usersToAdd.Count(user => user.CreatedOn == null || string.IsNullOrEmpty(user.PasswordHash));
_context.Users.AddRange(usersToAdd);
_context.PasswordHistory.AddRange(passwordHistories);
_context.SaveChanges();
}
catch (Exception e)
{
_logger.LogError(e, "error");
throw;
}
}
在添加到数据库之前,我什至检查是否有空值,但是没有。即使调试,我也看到对象已满。
从图像中可以看出,“ LastLogon”列中有些用户的字段为空。那不是唯一的领域。
为什么会发生这种情况,我该如何解决该问题?
编辑:我发现问题比我要奇怪。对于我要插入的每个用户,EF插入一个新条目将所有列都为空。因此,如果我要插入10个用户,则会插入这10个用户,但会将其他10个条目插入到用户表中,所有列均为空或null。仍然没有找出问题所在...