Apparently you have SBDS
and TRANSACTIONS
. Every Sbd
has a primary key Id
. Every Transaction has a primary key Id
and a foreign key to the Sbd
that it belongs to in SbdId
:
class Sbd
{
public int Id {get; set;} // Primary key
...
}
class Transaction
{
public int Id {get; set;} // Primary key
public int SbdId {get; set;} // Foreign key to the Sbd that this transaction belongs to
...
}
Now you want all Sdbs with an Id between 223 and 225, each Sbd with its Transaction with the highest value for Id.
Whenever you see a query for an object with all or some of its sub-objects
, like a School with its Students
, a Bank with his New York Clients
, a Customer with his Orders
, etc, consider using GroupJoin
// GroupJoin Sbds and Transactions:
var result = dbContext.Sbds.GroupJoin(dbContext.Transactions,
sbd => sbd.Id, // from every Sbd, take the Id
transaction => transaction.SbdId, // from every Transaction take the SbdId
// ResultSelector: take the Sbd with all its matching Transactions to make one new:
(sbd, transactionsOfThisSbd) => new
{
Id = sbd.Id,
// You don't want all transactions of this Sbd, you want only the transaction
// with the highest Id:
Transaction = transactionsOfThisSbd
.OrderByDescending(transaction => transaction.Id)
.FirstOrDefault(),
});
Or without all the comment, so you see how small the statement is:
var result = dbContext.Sbds.GroupJoin(dbContext.Transactions,
sbd => sbd.Id,
transaction => transaction.SbdId,
(sbd, transactionsOfThisSbd) => new
{
Id = sbd.Id,
Transaction = transactionsOfThisSbd
.OrderByDescending(transaction => transaction.Id)
.FirstOrDefault(),
});