Order
entity representing an order with properties such as Id
, OrderName
, and OrderDate
. We then create a OrderDbContext
class that inherits from DbContext
to interact with the database.using System;
using System.Linq;
public class Order
{
public int Id { get; set; }
public string OrderName { get; set; }
public DateTime OrderDate { get; set; }
}
public class OrderDbContext : DbContext
{
public DbSet<Order> Orders { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Configure your database connection here
optionsBuilder.UseSqlServer("YourConnectionString");
}
}
public class OrderManager
{
public Order GetLatestOrder()
{
using (var dbContext = new OrderDbContext())
{
// Query the Order table and order the results by OrderDate in descending order
var latestOrder = dbContext.Orders.OrderByDescending(o => o.OrderDate).FirstOrDefault();
return latestOrder;
}
}
}
// Usage
class Program
{
static void Main(string[] args)
{
var orderManager = new OrderManager();
var latestOrder = orderManager.GetLatestOrder();
if (latestOrder != null)
{
Console.WriteLine($"Latest Order: ID - {latestOrder.Id}, Name - {latestOrder.OrderName}, Date - {latestOrder.OrderDate}");
}
else
{
Console.WriteLine("No orders found in the database.");
}
}
}
The OrderManager
class contains a method GetLatestOrder
which queries the Orders
table, orders the results by OrderDate
in descending order, and retrieves the top-most record using FirstOrDefault
. Finally, in the Main
method of our program, we instantiate OrderManager
and call GetLatestOrder
to get the latest order from the database.