尝试使用 LINQ 填充文本框时出现问题

Problem trying to populate a text box using LINQ

我正在尝试使用以下对象 Entity Framework 和 LINQ 从数据库中使用本地办公室联系人的电子邮件地址填充文本框。 这是我正在使用的 LINQ:

var localContactsEmail = from office in context.Offices
                         where office.Address.ToString().Equals(selectedAddress)
                         select office.OfficeContacts.Email;

tbLocalOfficeEmail.Text = localContactsEmail.ToString();

如果我在 localContactsEmail 上使用 ToString(),文本框会显示:

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))

如果我在 localContactsEmail 上关闭 ToString(),我会收到以下错误:

错误 CS0029 无法将类型 'System.Linq.IQueryable' 隐式转换为 'string'

谁能告诉我为什么它不只返回电子邮件地址。

这是对象。

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; }
}

localContactsEmail 是可查询的。你能试试这个代码吗:

var localContactsEmail = (from office in context.Offices
                         where office.Address.ToString().Equals(selectedAddress)
                         select office.OfficeContacts.Email).FirstOrDefault();

tbLocalOfficeEmail.Text = localContactsEmail.ToString();替换为

  if (localContactsEmail.Any())
            {
                tbLocalOfficeEmail.Text = localContactsEmail.First().ToString();
            }