How to perform Join between multiple tables in LINQ lambda
我试图在LINQ中的多个表之间执行联接。 我有以下课程:
1 2 3 4 5 | Product {Id, ProdName, ProdQty} Category {Id, CatName} ProductCategory{ProdId, CatId} //association table |
我使用以下代码(其中
1 2 |
通过此代码,我从以下类中获取一个对象:
1 | QueryClass { productproductcategory, category} |
生产产品类别为:
1 | ProductProductCategoryClass {product, productcategory} |
我不明白联接的"表"在哪里,我期望一个包含来自所涉及类的所有属性的类。
我的目标是使用查询产生的一些属性填充另一个对象:
1 | CategorizedProducts catProducts = query.Select(m => new { m.ProdId = ???, m.CatId = ???, //other assignments }); |
我怎样才能实现这个目标?
对于联接,我强烈希望对所有隐藏的细节使用查询语法(并非最不重要的是中间投影所涉及的透明标识符,在点语法等效项中很明显)。但是,您询问了Lambda,我认为您拥有所需的一切-您只需要将它们放在一起即可。
1 2 3 4 5 6 7 8 |
如果需要,可以将联接保存到局部变量中,然后在以后重用,但是由于缺少其他细节,我认为没有理由引入局部变量。
同样,您可以将
1 2 3 4 5 6 7 |
...并最后尝试通过查询语法向您推销,看起来像这样:
1 2 3 4 5 6 7 8 9 | var categorizedProducts = from p in product join pc in productcategory on p.Id equals pc.ProdId join c in category on pc.CatId equals c.Id select new { ProdId = p.Id, // or pc.ProdId CatId = c.CatId // other assignments }; |
您的双手可能会被束缚在查询语法是否可用上。我知道有些商店有这样的要求-通常是基于查询语法比点语法受限制的观点。还有其他原因,例如"如果我可以用点语法做更多的事情,为什么还要学习第二种语法?"正如最后一部分所展示的那样-查询语法隐藏的细节可以使其值得一读,因为它带来了可读性的提高:所有必须准备的中间投影和标识符都不是正面而居中的语法版本中的阶段-它们是背景绒毛。现在关闭我的肥皂盒-不管怎样,谢谢您的提问。 :)
您所看到的就是所获得的-这正是您想要的,在这里:
1 |
那是一个lambda表达式,返回带有这两个属性的匿名类型。
在您的CategorizedProducts中,您只需要浏览以下属性:
1 2 3 4 5 6 | CategorizedProducts catProducts = query.Select( m => new { ProdId = m.productproductcategory.product.Id, CatId = m.category.CatId, // other assignments }); |
看一下我项目中的这个示例代码
1 2 3 4 5 6 7 8 9 10 11 12 | public static IList<Letter> GetDepartmentLettersLinq(int departmentId) { IEnumerable<Letter> allDepartmentLetters = from allLetter in LetterService.GetAllLetters() join allUser in UserService.GetAllUsers() on allLetter.EmployeeID equals allUser.ID into usersGroup from user in usersGroup.DefaultIfEmpty()// here is the tricky part join allDepartment in DepartmentService.GetAllDepartments() on user.DepartmentID equals allDepartment.ID where allDepartment.ID == departmentId select allLetter; return allDepartmentLetters.ToArray(); } |
在这段代码中,我加入了3个表,并从where子句中吐出了加入条件
注意:Services类只是扭曲(封装)数据库操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | public ActionResult Index() { List<CustomerOrder_Result> obj = new List<CustomerOrder_Result>(); var orderlist = (from a in db.OrderMasters join b in db.Customers on a.CustomerId equals b.Id join c in db.CustomerAddresses on b.Id equals c.CustomerId where a.Status =="Pending" select new { Customername = b.Customername, Phone = b.Phone, OrderId = a.OrderId, OrderDate = a.OrderDate, NoOfItems = a.NoOfItems, Order_amt = a.Order_amt, dis_amt = a.Dis_amt, net_amt = a.Net_amt, status=a.Status, address = c.address, City = c.City, State = c.State, Pin = c.Pin }) ; foreach (var item in orderlist) { CustomerOrder_Result clr = new CustomerOrder_Result(); clr.Customername=item.Customername; clr.Phone = item.Phone; clr.OrderId = item.OrderId; clr.OrderDate = item.OrderDate; clr.NoOfItems = item.NoOfItems; clr.Order_amt = item.Order_amt; clr.net_amt = item.net_amt; clr.address = item.address; clr.City = item.City; clr.State = item.State; clr.Pin = item.Pin; clr.status = item.status; obj.Add(clr); } |
已经有一段时间了,但我的回答可能会帮助某人:
如果您已经正确定义了关系,则可以使用以下方法:
1 2 3 4 5 | var res = query.Products.Select(m => new { productID = product.Id, categoryID = m.ProductCategory.Select(s => s.Category.ID).ToList(), }).ToList(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 | var query = from a in d.tbl_Usuarios from b in d.tblComidaPreferidas from c in d.tblLugarNacimientoes select new { _nombre = a.Nombre, _comida = b.ComidaPreferida, _lNacimiento = c.Ciudad }; foreach (var i in query) { Console.WriteLine($"{i._nombre } le gusta {i._comida} y nació en {i._lNacimiento}"); } |