asp.net剃须刀核心在帖子上插入多个记录

时间:2018-09-27 22:51:45

标签: razor entity-framework-core asp.net-core-2.0

我试图在发送电子邮件时创建电子邮件日志。

我创建了一个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");
}

0 个答案:

没有答案