我有一个名为CustomerGroup的表,它与表contact_List有许多关系。第三个表CustomerGroupContact具有两个表的主键。
这是CustomerGroup表的样子:
public class CustomerGroup
{
public CustomerGroup()
{
CustomerGroupContacts = new HashSet<CustomerGroupContact>();
}
[Key]
public int Customer_Group_Code { get; set; }
public int Customer_Code { get; set; }
public string Customer_Group_Name { get; set; }
public virtual ICollection<CustomerGroupContact> CustomerGroupContacts { get; set; }
}
这是Contact_List模型的样子:
public class Contact_List
{
[Key]
public int Contact_List_Code { get; set; }
public int Customer_Code { get; set; }
public string First_Name { get; set; }
public string Last_Name { get; set; }
public string Contact_No { get; set; }
}
我正在尝试加入2个表来创建一个看起来像下面模型的对象:
public class Contacts
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string ContactNo { get; set; }
public string GroupName { get; set; }
}
我正在努力使用正确的查询语句,该语句将基于customer_code属性加入表。 我会感激任何帮助。
答案 0 :(得分:1)
请尝试以下操作:
List<CustomerGroup> groups = new List<CustomerGroup>();
List<Contact_List> contact_list = new List<Contact_List>();
List<Contacts> contacts = (from g in groups
join c in contact_list on g.Customer_Code equals c.Customer_Code
select new { groupName = g.Customer_Group_Name, c })
.Select(x => new Contacts() {
FirstName = x.c.First_Name,
LastName = x.c.Last_Name,
ContactNo = x.c.Contact_No,
GroupName = x.groupName
}).ToList();
答案 1 :(得分:0)
这会有用吗?
private IEnumerable<Contacts> JoinTables(IEnumerable<Contact_List> contactLists, IEnumerable<CustomerGroup> customerGroups)
{
return contactLists.Join(customerGroups,
x => x.Customer_Code,
y => y.Customer_Code,
(x, y) => new Contacts()
{
ContactNo = x.Contact_No,
FirstName = x.First_Name,
LastName = x.Last_Name,
GroupName = y.Customer_Group_Name
});
}
答案 2 :(得分:-1)
希望这会奏效:
var userContactList = (from custGroup in _db.CustomerGroup
join cList in _db.Contact_List
on custGroup.Customer_Code equals cList.Customer_Code
select new Contacts {
FirstName = cList.First_Name,
LastName = cList.Last_Name,
ContactNo = cList.Contact_No,
GroupName = custGroup.Customer_Group_Name
}).ToList();