How to use LINQ Query Syntax to populate a GridView in C#
I am trying to populate a GridView in Windows Forms using Entity Framework. I have the following classes with this data.
Class Office
OfficeId
Region
Address
City
[ForeignKey("OfficeContactId")]
public virtual OfficeContact OfficeContacts
[ForeignKey("RegionalTechnicianId")]
public virtual RegionalTechnician RegionalTechnicians
Class OfficeContact
OfficeContactId
Name
Email
Phone
Class RegionalTechnician
RegionalTechnicianId
Name
Email
Phone
The following works fine to populate the GridView with the Office data (OfficeId, Region, Address, City) but I am not sure how to pull in the other data.
dataGridView.DataSource = context.Offices.ToList<Office>();
Solution 1:
dataGridView.DataSource = (from office in context.Offices
join OfficeContact in context.OfficeContacts on office.OfficeId equals OfficeContact.OfficeContactId
join RegionalTechnician in context.RegionalTechnicians on office.OfficeId equals RegionalTechnician.RegionalTechnicianId
select new
{
OfficeId = office.OfficeId,
Region = office.Region,
Address = office.Address,
City = office.City,
OfficeContactId = OfficeContact.OfficeContactId,
OfficeContactName = OfficeContact.Name,
OfficeContactEmail = OfficeContact.Email,
OfficeContactPhone = OfficeContact.Phone,
RegionalTechnicianId = RegionalTechnician.RegionalTechnicianId,
RegionalTechnicianName = RegionalTechnician.Name,
RegionalTechnicianEmail = RegionalTechnician.Email,
RegionalTechnicianPhone = RegionalTechnician.Phone
}).ToList();
Solution 2:
tow solution
-
using LINQ.
please visit this page.
show-properties-of-a-navigation-property-in-datagridview-second-level-propertie
-
Create view in database and view model in Code.
For Example :
Create View officeView
as
Select o.OfficeId,
o.Region,
o.Address,
o.City,
r.Email,
r.Name,
r.Phone
From Office o
left join RegionalTechnician r on r.RegionalTechnicianId= o.RegionalTechnicianId
left join OfficeContact oc on oc.OfficeContactId= o.OfficeContactId
In code: Update Context(Entity Framework)
After Update Context, you have model like this
public partial class officeView
{
public long OfficeId { get; set; }
public string Region { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Email { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
}
Then:
dataGridView.DataSource = context.officeViews.ToList();