In my application you can assign tasks (TaskDetails) to a person (Employee) who then receives an email notification on his/her email address pulled from the db containing the title of the task. I'm using Postal for this.
In the Create method for TaskDetails I added:
[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);
}
My email view:
@model MyApp.Models.NewTaskEmail
From: mailer@example.com
To: @Model.ToEmail
Subject: You have a new task
Hi @Model.ToFirstname,
//rest of email body
When debugging I can see that ToEmail and ToFirstname have the right value, but this is the resulting email:
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
The hardcoded string is recognized correctly, but the string that resulted from the db query (Employee.FirstName) is displayed as the query itself. What am I doing wrong?
var emplName = from e in db.Employees
where e.EmployeeId.Equals(taskDetails.EmployeeId)
select e.FirstName;
emplName
is a collection of string, so you will need to use FirstOrDefault()
var emplName = (from e in db.Employees
where e.EmployeeId == taskDetails.EmployeeId
select e.FirstName).FirstOrDefault();