我试图在发送电子邮件时创建电子邮件日志。
我创建了一个foreach循环,将记录添加到数据库中。
但是,我只能在await _context.SaveChangesAsync();
不在循环中时添加一条记录。
如果将await _context.SaveChangesAsync();
放入其中,则会出现以下错误。
SqlException:当IDENTITY_INSERT设置为OFF时,无法为表'EmailLog'中的标识列插入显式值
代码:
public async Task<IActionResult> OnPostAsync(IEnumerable<int> emailuser)
{
//get login user
var claimsIdentity = (ClaimsIdentity)this.User.Identity;
var claim = claimsIdentity.FindFirst(ClaimTypes.Name);
var TestAimItem = _context.AimItem.Where(x => emailuser.Contains(x.Id)).ToList();
foreach (var item in TestAimItem.GroupBy(item => item.Email))
{
EmailMessage = await _context.EmailMessage.SingleOrDefaultAsync(m => m.Id == 2);
string EmailAddress = (item.Key);
var emailMessage1 = EmailMessage.MessageBody.Replace(Environment.NewLine, "<br/>");
var linkHtml = "<a href=" + '"' + "https://" + EmailMessage.Link + '"' + ">here</a>";
var emailMessage2 = emailMessage1.Replace("HPWDLINK", "click " + linkHtml);
var emailMessage3 = emailMessage2.Replace("HPWDUSEREMAIL", EmailAddress);
var emailMessage4 = HttpUtility.HtmlDecode(emailMessage3);
await _emailSender.SendEmailAsync(To, EmailMessage.MessageSubject, emailMessage4);
}
foreach (var item1 in TestAimItem)
{
EmailLog.EmailDate = DateTime.Now;
EmailLog.MessageId = 2;
EmailLog.SentTo = item1.Email;
EmailLog.SentBy = claim.Value;
//submit record
_context.EmailLog.Add(EmailLog);
//await _context.SaveChangesAsync();
}
await _context.SaveChangesAsync();
return RedirectToPage("/UserReporting/EmailUsersAnnualReport");
}