使用Postal创建的电子邮件包含数据库查询而不是字符串值

时间:2017-04-12 19:30:22

标签: asp.net-mvc linq postal

在我的应用程序中,您可以将任务(TaskDetails)分配给某个人(Employee),然后他们会从包含任务标题的数据库中提取的电子邮件地址收到电子邮件通知。我正在使用Postal。

在TaskDetails的Create方法中,我添加了:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(TaskDetails taskDetails)
{
    if (ModelState.IsValid)
    {
        db.Tasks.Add(taskDetails);
        db.SaveChanges();
        //Extra code for email notification to Employee when new Task is created
        //See: http://aboutcode.net/postal
        var emplName =   from e in db.Employees
                        where e.EmployeeId.Equals(taskDetails.EmployeeId)
                       select e.FirstName;
        try
        {
            var email = new NewTaskEmail
            {
                ToEmail = "testio@testing.com"
                ToFirstname = emplName.toString()
            };
            email.Send();
        }
        catch (Exception ex)
        {
            return View("Error", new HandleErrorInfo(ex, "TaskDetails", "Create"));
        }
        //end of extra code for email notification
        return RedirectToAction("Index");
    }
//some viewbag code
    return View(taskDetails);
}

我的电子邮件视图:

@model MyApp.Models.NewTaskEmail

From: mailer@example.com
To: @Model.ToEmail
Subject: You have a new task 

Hi @Model.ToFirstname,
//rest of email body

调试时我可以看到ToEmail和ToFirstname具有正确的值,但这是生成的电子邮件:

X-Sender: mailer@example.com
X-Receiver: testio@testing.com
MIME-Version: 1.0
From: mailer@example.com
To: testio@testing.com
Date: 12 Apr 2017 21:11:33 +0200
Subject: You have a new task
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: quoted-printable

Hi SELECT =0D=0A    [Extent1].[FirstName] AS [FirstName]=0D=0A   =
 FROM [dbo].[Employee] AS [Extent1]=0D=0A    WHERE [Extent1].[Emp=
loyeeId] =3D @p__linq__0,=0D=0A=0D=0A

正确识别硬编码字符串,但db查询(Employee.FirstName)产生的字符串显示为查询本身。 我做错了什么?

1 个答案:

答案 0 :(得分:0)

var emplName = from e in db.Employees
   where e.EmployeeId.Equals(taskDetails.EmployeeId)
   select e.FirstName;

emplName是字符串的集合,因此您需要使用FirstOrDefault()

var emplName = (from e in db.Employees
   where e.EmployeeId == taskDetails.EmployeeId
   select e.FirstName).FirstOrDefault();