如何使用 LINQ 查询语法在 C# 中填充 GridView

How to use LINQ Query Syntax to populate a GridView in C#

我正在尝试使用 Entity Framework 在 Windows 表单中填充 GridView。我有以下 类 和这些数据。

    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

以下方法可以很好地使用 Office 数据(OfficeId、地区、地址、城市)填充 GridView,但我不确定如何提取其他数据。

dataGridView.DataSource = context.Offices.ToList<Office>();
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();

牵引解决方案

  1. 使用 LINQ。

    请访问此页面。

  2. 在数据库中创建视图并在代码中查看模型。

例如:

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

在代码中:更新上下文(Entity Framework)

更新上下文后,你有这样的模型

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

然后:

dataGridView.DataSource = context.officeViews.ToList();