[英]query many to many relationship with Linq
我有一個名為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屬性加入表。 我將不勝感激。
嘗試以下操作:
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();
這行得通嗎?
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
});
}
希望這會起作用:
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.