Adding new items dynamically to IQueryable hard-coded fake repository

rem picture rem · Sep 18, 2010 · Viewed 20.2k times · Source

Building an application, before using a real database, just to get things work I can first use a hard-coded list as a fake, in-memory repository:

public class FakeProductsRepository 
{
    private static IQueryable<Product> fakeProducts = new List<Product> {
        new Product{ ProductID = "xxx", Description = "xxx", Price = 1000},
        new Product{ ProductID = "yyy", Description = "xxx", Price = 2000},
        new Product{ ProductID = "zzz", Description = "xxx", Price = 3000}
    }.AsQueryable();

    public IQueryable<Product> Products
    {
        get { return fakeProducts; }
    }
}

How to add a method to this class for adding new, not hard-coded items in this list dynamically?

Answer

dtb picture dtb · Sep 18, 2010

Just keep the List<Product> in a field of type List<Product> instead of IQueryable<Product>:

public class FakeProductsRepository 
{
    private readonly List<Product> fakeProducts = new List<Product>
    {
        new Product { ProductID = "xxx", Description = "xxx", Price = 1000 },
        new Product { ProductID = "yyy", Description = "xxx", Price = 2000 },
        new Product { ProductID = "zzz", Description = "xxx", Price = 3000 },
    };

    public void AddProduct(string productID, string description, int price)
    {
        fakeProducts.Add(new Product
        {
            ProductID = productID,
            Description = description,
            Price = price,
        });
    }

    public IQueryable<Product> Products
    {
        get { return fakeProducts.AsQueryable(); }
    }
}