1
我找一模一樣的NHibernate的多個子集在lambda表達式查詢*
How to efficiently query with filter on children at different levels?
而是「lambda表達式」語法。
我真的需要這個,任何人都可以幫忙嗎?謝謝!
我找一模一樣的NHibernate的多個子集在lambda表達式查詢*
How to efficiently query with filter on children at different levels?
而是「lambda表達式」語法。
我真的需要這個,任何人都可以幫忙嗎?謝謝!
下面是從後的代碼片段,你在這兩種查詢語法和lambda語法引用:https://stackoverflow.com/a/12324116/670028:
LINQ查詢語法:
var listOfString = new List<string>() { "String1", "String2" };
var customers =
(
from a in session.Query<A>()
from b in a.B
from c in b.C
where a.Status == "Active"
&& listOfStrings.Contains(b.SomeField)
&& listOfStrings.Contains(c.someOtherField)
select a)
.ToList();
LINQ lambda語法:
var listOfString = new List<string>() { "String1", "String2" };
var customers =
(
session.Query<A>()
.SelectMany(a => a.B, (a, b) => new { a, b })
.SelectMany(@t => b.C, (@t, c) => new { @t, c })
.Where(@t => a.Status == "Active"
&& listOfStrings.Contains(b.SomeField)
&& listOfStrings.Contains(c.someOtherField)).
Select
(@t => a))
.ToList();
正如您所看到的,它不像LINQ查詢語法那樣「乾淨」,因爲每次使用.SelectMany時都必須繼續投影到新的匿名類型中() 方法。它也可能與所有這些變量名稱有點混淆,這就是爲什麼當我需要執行像這樣的查詢時,我傾向於使用LINQ查詢語法而不是lambda表達式。
而只是爲了好玩,這裏是用.SelectMany(),看起來通過給匿名類型更有意義的名稱更好一點,更現實的例子:
public void Get_StarPowerCorporations_PendingShipment_Orders_Shipping_To_NewYork_Or_Chicago()
{
var session = UnitOfWork.Current.GetSession();
var listOfCities = new List<string> { "New York", "Chicago" };
var customerAndOrders = session.Query<Customer>()
.SelectMany(c => c.Orders, (Customer, Orders) => new { Customer, Orders })
.SelectMany(CustomerAndOrders => CustomerAndOrders.Orders.OrderDetails, (CustomerAndOrders, OrderDetails) => new { CustomerAndOrders, OrderDetails })
.Where(x => x.CustomerAndOrders.Customer.CompanyName == "StarPower Corporatation"
&& x.CustomerAndOrders.Orders.Status == "Pending Shipment"
&& listOfCities.Contains(x.OrderDetails.City))
.Select(x => x.CustomerAndOrders.Customer)
.Fetch(x => x.Orders)
.ToList();
}
public class Customer
{
public int CustomerId { get; set; }
public string CompanyName { get; set; }
public IList<Address> Addresses { get; set; }
public IList<Order> Orders { get; set; }
}
public class Address
{
public int AddressId { get; set; }
}
public class Order
{
public int OrderId { get; set; }
public string Status { get; set; }
public IList<OrderDetail> OrderDetails { get; set; }
}
public class OrderDetail
{
public int OrderDetailId { get; set; }
public string City { get; set; }
}
非常感謝,正是我需要的。是的,語法不是「乾淨」的,但是這種表達式可以動態地與LINQ語法形成對比。 – Alexandr