尝试在 C# 中使用 LINQ 填充组合框但未获得任何结果

Trying to populate a combox box using LINQ in C# but not getting any results

我正在尝试使用以下对象 Entity Framework 和 LINQ 从数据库中填充一个包含本地办公室联系人姓名列表的组合框。它不返回任何结果。任何人都可以帮忙吗? 类 看起来像这样。

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

LINQ 看起来像这样。

private void cbAddress_SelectionChangeCommitted(object sender, EventArgs e)
{
     var localContact = from office in context.Offices.ToList()
                        where office.OfficeContacts.Equals(office.OfficeContactId)
                        select Name;

     cbLocalOfficeContactName.DataSource = localContact.ToList();
}

试试这个


     var localContacts = context.Offices
                        .Select(o=>o.OfficeContacts.Name)
                        .ToList();
     cbLocalOfficeContactName.DataSource = localContacts;

首先,从 in context.Offices 中删除 .ToList()。此处的 ToList() 会导致 EF 在应用 Where 子句之前从数据库加载 all 个办公室。

接下来,下面的 Where 子句没有任何意义:

where office.OfficeContacts.Equals(office.OfficeContactId)

这更像是一个 Join 子句,而不是 Where 条件。当 EF 设置了导航属性时,相关实体之间的连接完全在后台处理。

如果您想 select 每个办公室的办公室联系人姓名,您只需要 Select 来自相关实体的姓名。然后,您可以在使用 ToList():

加载之前获取数据
 var localContacts = (from office in context.Offices
                    select office.OfficeContacts.Name).ToList();

在 Where 子句中,您只需要来自符合条件的特定办公室的联系人。例如,如果您只想要特定区域中办公室的联系人姓名:

 var localContacts = (from office in context.Offices
                    where office.Region = localRegion
                    select office.OfficeContacts.Name).ToList();

其中 localRegion 是传入值或计算值,用于限制办公室 select 离子。

从那里你可以在这里放一个断点,让它执行,看看你是否得到任何localContacts。如果您没有看到任何数据,那么最常见的罪魁祸首是在运行时 DbContext 使用的连接字符串与您预期的不同,并且它没有您希望它找到的数据。仔细检查 web.config 或 .exe.config 文件中的连接字符串。此问题的常见原因是将 DbContext 和实体移动到不同的程序集并更新 DLL app.config 中的连接字符串,其中它没有反映仍在主应用程序配置中的设置。