问题描述
我正在开发一个 ASP.NET Core 5.0 MVC 应用程序,在创建包含所有答案的记录后,我使用 Mailkit Nuget 包向客户端发送电子邮件。我已将与 Mailkit 相关的代码放在 Create(Post) 方法中,但在创建和发送电子邮件后,当我像 sale.ProductType 一样编写名为 Product Type 的字段时,我在 Mailkit 代码部分中收到 System.NullReferenceException。 ProductTypeDesc 基本上是一个下拉列表,有一个查找表,因此是主表(Sale)的外键。但它与 sale.ProductTypeId 一起工作,这不是我想要的。谁能给我解决方案?
这是我的模型:
使用系统;
使用 System.Collections.Generic;
#nullable 禁用
命名空间 Sale_app.Models
{
public partial class Sale
{
public int SaleId { get; set; }
public string ProductName { get; set; }
public string ProductTypeId { get; set; }
public virtual ProductType ProductType { get; set; }
}
}
使用系统;
使用 System.Collections.Generic;
#nullable 禁用
命名空间 Sale_app.Models
{ 公共部分类 ProductType
{
public ProductType()
{
Sales = new HashSet<Sale>();
}
public int ProductTypeId { get; set; }
public string ProductTypeDesc { get; set; }
public virtual ICollection<Sale> Sales { get; set; }
}
}
这些是我的控制器中的 Create 方法:
//获取销售
公共 IActionResult 创建()
{
ViewBag.ProductTypeList = _context.ProductType.ToList();
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create([Bind("SaleId,ProductTypeId,ProductName")] Sale sale)
{
if (ModelState.IsValid)
{
try
{
_context.Add(sale);
_context.SaveChanges();
//instantiate a new MimeMessage
var message = new MimeMessage();
//Setting the To e-mail address
message.To.Add(new MailBoxAddress("E-mail Recipient Name","an email address comes here"))
//Setting the From e-mail address
message.From.Add(new MailBoxAddress("Sale Form " + "Response","an email address comes here"));
//E-mail subject
message.Subject = "Sale Form";
//E-mail message body
message.Body = new TextPart(textformat.Html)
{
Text = "<b>SaleId:</b> " + sale.SaleId + "<br/>" + "<b>ProductName:</b> " + sale.ProductName + "<br/>" +
"<b>ProductType</b>: " + sale.ProductType.ProductTypeDecs
};
//Configure the e-mail
using (var emailClient = new SmtpClient())
{
emailClient.Connect("smtp.gmail.com",587,false);
emailClient.Authenticate("an email address comes here","a password comes here");
emailClient.Send(message);
emailClient.disconnect(true);
}
return RedirectToAction(nameof(Index));
}
catch (Exception ex)
{
ModelState.Clear();
ViewBag.Message = $" Oops! We have a problem here {ex.Message}";
}
}
return View(sale);
}
解决方法
更改您的代码:
_context.Add(sale);
_context.SaveChanges();
var newSale= _context.Sales
.Include(i=> i.ProductType)
.Where(i=> i.SaleId=sale.SaleId)
.FirstOrDefault();
......
......
message.Body = new TextPart(TextFormat.Html)
{
Text = "<b>SaleId:</b> " + newSale.SaleId + "<br/>" + "<b>ProductName:</b> " + newSale.ProductName + "<br/>" +
"<b>ProductType</b>: " + newSale.ProductType.ProductTypeDecs
};