I am trying to populate a text box with the email address of a local office contact from a database using the following Objects, Entity Framework and LINQ. This is the LINQ that I am using:
var localContactsEmail = from office in context.Offices
where office.Address.ToString().Equals(selectedAddress)
select office.OfficeContacts.Email;
tbLocalOfficeEmail.Text = localContactsEmail.ToString();
If I use ToString() on localContactsEmail the text box displays this:
SELECT
[Extent2].[Email] AS [Email] FROM [dbo].[Offices] AS [Extent1]
INNER JOIN [dbo].[OfficeContacts] AS [Extent2] ON [Extent1].[OfficeContactId] = [Extent2].[OfficeContactId]
WHERE ((CASE WHEN ([Extent1].[Address] IS NULL) THEN N'' ELSE [Extent1].[Address] END) = @p__linq__0) OR ((CASE WHEN ([Extent1].[Address] IS NULL) THEN N'' ELSE [Extent1].[Address] END IS NULL) AND (@p__linq__0 IS NULL))
If I leave off ToString() on localContactsEmail I get the following error:
Error CS0029 Cannot implicitly convert type 'System.Linq.IQueryable' to 'string'
Can anyone tell me why it is not returning just the email address.
Here are the objects.
public class OfficeContact
{
[Key]
public int OfficeContactId { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
}
public class Office
{
[Key]
public int OfficeId { get; set; }
public string Region { get; set; }
public string Address { get; set; }
public string City { get; set; }
[Display(Name = "OfficeContact")]
public virtual int OfficeContactId { get; set; }
[ForeignKey("OfficeContactId")]
public virtual OfficeContact OfficeContacts { get; set; }
}
CodePudding user response:
localContactsEmail is IQueryable. Can you try this code:
var localContactsEmail = (from office in context.Offices
where office.Address.ToString().Equals(selectedAddress)
select office.OfficeContacts.Email).FirstOrDefault();
CodePudding user response:
replace tbLocalOfficeEmail.Text = localContactsEmail.ToString();
to
if (localContactsEmail.Any())
{
tbLocalOfficeEmail.Text = localContactsEmail.First().ToString();
}