I am trying to populate a combox box with a list of local office contact names from a database using the following Objects, Entity Framework and LINQ. It is not returning any results. Can anyone please help with this? The classes look like this.
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; }
}
The LINQ looks like this.
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();
}
CodePudding user response:
First thing, remove the .ToList()
from in context.Offices
. A ToList()
here would cause EF to load all offices from the DB before applying the Where
clause.
Next, the following Where clause doesn't make any sense:
where office.OfficeContacts.Equals(office.OfficeContactId)
This is more like a Join
clause, not a Where
condition. When EF is set up with navigation properties, the join between related entities is handled entirely behind the scene.
If you want to select the Office Contact Name for every office, you need only to Select
the name from the related entity. You can then get the data prior to loading with ToList()
:
var localContacts = (from office in context.Offices
select office.OfficeContacts.Name).ToList();
The Where clause would be where you only want contacts from specific offices that match a condition. Such as if you only want contact names for an office in a particular Region:
var localContacts = (from office in context.Offices
where office.Region = localRegion
select office.OfficeContacts.Name).ToList();
Where localRegion
is a passed in or computed value to limit your office selections.
From there you can put a breakpoint here, let it execute, and see if you get any localContacts. If you are not seeing any data then the most common culprit is that at runtime the DbContext is using a different connection string than you expect and it doesn't have the data you expect it to find. Double check the connection string in your web.config or .exe.config file. Common causes for this issue is moving the DbContext and entities to a different assembly and updating the connection string in the DLL's app.config where it doesn't reflect the setting still in the main application's configuration.
CodePudding user response:
try this
var localContacts = context.Offices
.Select(o=>o.OfficeContacts.Name)
.ToList();
cbLocalOfficeContactName.DataSource = localContacts;