使用2个实体的字段创建新列表

时间:2018-01-03 16:16:48

标签: c# winforms linq lambda

我有2个实体:EmployeesSendMessage

public class Employee
{
    [DbColumn(IsIdentity =true, IsPrimary =true)]
    public long EmployeeId { get; set; }
    [DbColumn]
    public string Name { get; set; }
    [DbColumn]
    public string Surname { get; set; }
    [DbColumn]
    public string Date_Birth { get; set; }
    [DbColumn]
    public string Home_Address { get; set; }

    [DbColumn]
    public string City { get; set; }
    [DbColumn]
    public string Postcode { get; set; }
    [DbColumn]
    public string Telephone { get; set; }
    [DbColumn]
    public string Mobile { get; set; }
    [DbColumn]
    public string Email { get; set; }
    [DbColumn]
    public long ShiftId { get; set; }
}

正如您所看到的,EmployeeId字段是连接两个

public class MessageSent
{
    [DbColumn(IsIdentity =true, IsPrimary =true)]
    public long MessageSentId { get; set; }
    [DbColumn]
    public long EmployeeId { get; set; }
    [DbColumn]
    public long MessageSentSeq { get; set; }
    [DbColumn]
    public string Status { get; set; }
    [DbColumn]
    public string DateSent { get; set; }

}

要兑换我使用以下方法

gvEmployee.DataSource = new EmployeeService().GetAll();

现在需要我需要在新屏幕上显示以下字段: 表MessageSentId,EmployeeId,MessageSentSeq的表MessageSent Name,Surname的{​​{1}}。

如何创建包含这5个字段的第三个列表来填充我的网格?

1 个答案:

答案 0 :(得分:3)

带你的员工:

var employees = new EmployeeService().GetAll();

然后你的消息:

var messages = new MessageSentService().GetAll(); // probably like this, idk what its in your code

使用LINQ查询语法更清晰,更自然,并且更容易发现错误:

var query = 
    from employee in employees
    join message in messages
    on employee.EmployeeId equals message.EmployeeId 
    select new { 
        MessageSentId = message.MessageId,
        EmployeeId = message.EmployeeId,
        MessageSentSeq = message.MessageSentSeq,
        Name = employee.Name,
        Surname = employee.Surname
    };

然后您可以使用query及其字段。