我有2个表stock
和stockprice
。我想使用Entity Framework 6获得所有股票的最新更新价格。
我先select * from stock
,然后使用foreach获取每个符号的最新更新价格。如何只使用实体框架6进行一次查询?
库存:
Id Symbol
-------------
1 AAPL
2 MSFT
Stockprice :
Id Symbol Price LastUpdatedDate
-------------------------------------
1 AAPL 120 11/7/2016
2 AAPL 121 11/2/2016
3 AAPL 123 11/3/2016
4 MSFT 111 11/2/2016
5 MSFT 101 11/6/2016
我想获得每个符号的最新更新价格。
AAPL 120 11/7/2016
MSFT 101 11/6/2016
答案 0 :(得分:2)
如果您有包含属性的对象列表 编号,符号,价钱,LastUpdatedDate
让我们说
List<ItemPrice> itemPrice
然后你可以这样做
var lastUpdated= from item in itemPrice
group item by item.Symbol into itemGroup
let maxDate = itemGroup.Max(gt => gt.LastUpdatedDate)
select new RegistrationModel
{
Symbol = itemGroup.Key,
LastUpdatedDate= maxDate,
Price= itemGroup.First(gt2 => gt2.ExpiryDateAD == maxDate).Price
}).ToList()
我希望它可以帮到你
答案 1 :(得分:0)
注意:我意识到您更喜欢纯EF解决方案,但这是另一种方法,我认为它更具可扩展性和可支持性。
查询:
Select A.Symbol, C.Price, A.MaxDate
(
Select Max(LastUpdatedDate) as MaxDate, Symbol
FROM stockprice A INNER JOIN stock B on A.Symbol = B.Symbol
Group By Symbol
) A
INNER JOIN StockPrice C on A.Symbol = C.Symbol AND A.MaxDate = C.LastUpdatedDate
制作视图:
Create View vStockPrice AS
Select A.Symbol, C.Price, A.MaxDate
(
Select Max(LastUpdatedDate) as MaxDate, Symbol
FROM stockprice A INNER JOIN stock B on A.Symbol = B.Symbol
Group By Symbol
) A
INNER JOIN StockPrice C on A.Symbol = C.Symbol AND A.MaxDate = C.LastUpdatedDate
Go
使用存储过程执行此操作:
Create Procedure usp_StockPrice AS
Begin
Select A.Symbol, C.Price, A.MaxDate
(
Select Max(LastUpdatedDate) as MaxDate, Symbol
FROM stockprice A INNER JOIN stock B on A.Symbol = B.Symbol
Group By Symbol
) A
INNER JOIN StockPrice C on A.Symbol = C.Symbol AND A.MaxDate = C.LastUpdatedDate
END
然后,您只需查询视图,就像使用EF查询任何表或使用该过程调用存储过程一样。
var query = from rows in vStockPrice select ..... ;
在View或SP中执行此操作的优点是,您只需更改基本查询即可处理将来对您的需求的任何更改。 (假设您想忽略便士股票,所以它只需要一个where子句:其中价格> 1.0)。您不必重新编译C#代码(并且您的DBA会因其他原因而喜欢这种方法!!)
如果您希望我扩展(或者您认为这不相关),请告诉我。
答案 2 :(得分:0)
试试这个
using(var db= new DbContext())
{
//This will fetch all your stock and include all corresponding StockPrices.
var stockWithPrices = db.Stock
.Select(x=> new
{
Name = x. Name
Price = x.StockPrices.OrderByDescending(y=>y.LastUpdatedDate).FirstOrDefault().Price
Date = x.StockPrices.OrderByDescending(y=>y.LastUpdatedDate).FirstOrDefault().Date
}.ToList();
}
假设您的模型看起来像这样
public partial class Stock
{
public int Id {get;set;}
public string Symbol {get;set;}
public ICollection<StockPrice> StockPrices {get;set;}
}