Contents tagged with linq

  • Repository and Unit of Work for Entity Framework (EF4) for Unit Testing

    Tags: Entity Framework, c#, linq, EF4

    If you are not familiar with the Unit of Work pattern you should firt look at Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application (9 of 10).  It's a great article that demonstrates what the Unit of Work pattern can do.

    Unfortunately, that article uses a different version of Entity Framework.  I am using the default tools that come with Visual Studio and didn't want to modify the project too greatly so for me, the code wasn't usable.  I also wanted to expose the IQueryable interface which as a side effect also simplified my Repository design.

    By using a Repository Pattern you'll find unit testing is now possible and quite easy to write.  This illustration (taken from asp.net) shows the differences between No Repository and the Repository Pattern.  Notice how there are no Unit Tests in the No Repository section also note the "Alternative Persistence Medium" node (this is where our MemoryRepository comes in).

    The Unit of Work

    The job of the Unit of Work class is to manage the lifecycle and context of your Repositories.  The class is pretty simple to create, implement IDisposable, add all your Repositories and give it a Save method.

    This is what Northwind's Interface and Unit of Work class looks like:

    (for the Repository code, check out my previous post: Generic IQueryable Repository for Entity Framework 4)

    public interface INorthwindUnitOfWork : IDisposable
    {
    	IRepository<Category> CategoryRepository { get; }
    	IRepository<Customer> CustomerRepository { get; }
    	IRepository<Employee> EmployeeRepository { get; }
    	IRepository<Order> OrderRepository { get; }
    	IRepository<Order_Detail> Order_DetailRepository { get; }
    	IRepository<Product> ProductRepository { get; }
    	IRepository<Shipper> ShipperRepository { get; }
    	IRepository<Supplier> SupplierRepository { get; }
            void Save();
    }
    
    public partial class NorthwindUnitOfWork : INorthwindUnitOfWork
    {
    	private readonly NorthwindDataContext _context;
    	private readonly IRepository<Category> _categoryRepository;
    	private readonly IRepository<Customer> _customerRepository;
    	private readonly IRepository<Employee> _employeeRepository;
    	private readonly IRepository<Order> _orderRepository;
    	private readonly IRepository<Order_Detail> _order_DetailRepository;
    	private readonly IRepository<Product> _productRepository;
    	private readonly IRepository<Shipper> _shipperRepository;
    	private readonly IRepository<Supplier> _supplierRepository;
    
    	public IRepository<Category> CategoryRepository
    	{
    		get { return _categoryRepository; }
    	}
    
    	public IRepository<Customer> CustomerRepository
    	{
    		get { return _customerRepository; }
    	}
    
    	public IRepository<Employee> EmployeeRepository
    	{
    		get { return _employeeRepository; }
    	}
    
    	public IRepository<Order> OrderRepository
    	{
    		get { return _orderRepository; }
    	}
    
    	public IRepository<Order_Detail> Order_DetailRepository
    	{
    		get { return _order_DetailRepository; }
    	}
    
    	public IRepository<Product> ProductRepository
    	{
    		get { return _productRepository; }
    	}
    
    	public IRepository<Shipper> ShipperRepository
    	{
    		get { return _shipperRepository; }
    	}
    
    	public IRepository<Supplier> SupplierRepository
    	{
    		get { return _supplierRepository; }
    	}
    
    	public NorthwindUnitOfWork(NorthwindDataContext context)
    	{
    		_context = context;
    
    		_categoryRepository = new EntityRepository<Category>(_context);
    		_customerRepository = new EntityRepository<Customer>(_context);
    		_employeeRepository = new EntityRepository<Employee>(_context);
    		_orderRepository = new EntityRepository<Order>(_context);
    		_order_DetailRepository = new EntityRepository<Order_Detail>(_context);
    		_productRepository = new EntityRepository<Product>(_context);
    		_shipperRepository = new EntityRepository<Shipper>(_context);
    		_supplierRepository = new EntityRepository<Supplier>(_context);
    	}
    
    	public void Save()
    	{
    		_context.SaveChanges();
    	}
    
    	#region IDisposable Methods
    
    	private bool disposed = false;
    
    	protected virtual void Dispose(bool disposing)
    	{
    		if (!this.disposed)
    		{
    			if (disposing)
    			{
    				_context.Dispose();
    			}
    		}
    		this.disposed = true;
    	}
    
    	public void Dispose()
    	{
    		Dispose(true);
    		GC.SuppressFinalize(this);
    	}
    
    	#endregion
    }
    
    

    Unit Testing

    (In this example I'm using Moq as my Mocking Framework)

    I start by creating a method called GetMockCategoryRepository that creates a new MemoryRepository object and returns returns an IRepository<Category>.  This will mimic the behavior of our Category Repository with an in memory list, allowing us to test without hitting the database.

    private IRepository<Category> GetMockCategoryRepository()
    {
    	var value = new MemoryRepository<Category>();
    	value.Add(new Category { Category_ID = 1, Category_Name = "Beverages" });
    	value.Add(new Category { Category_ID = 2, Category_Name = "Condiments" });
    	value.Add(new Category { Category_ID = 3, Category_Name = "Confections" });
    	return value;
    }
    

    Then in my test, I create a Mock INorthwindUnitOfWork, setup the CategoryRepository method to return my MemoryRepository and initialize a new NorthwindService object. For the Assert, we just need to check the count of items returned from the service is the same as our Repository!

    [TestMethod]
    public void NorthwindService_GetCategories_returns_category_names()
    {
    	// Arrange
    	var mockUnitOfWork = new Mock<INorthwindUnitOfWork>();
    	var mockCategories = GetMockCategoryRepository();
    
    	mockUnitOfWork.SetupGet(x => x.CategoryRepository)
    	              .Returns(mockCategories);
    
    	var northwindService = new NorthwindService(mockUnitOfWork.Object);
    
    	// Act
    	var categories = northwindService.GetCategories();
    
    	// Assert
    	Assert.AreEqual(mockCategories.All().Count(), categories.Length);
    }
    

    Well, that's all you need.  You are now ready to full unit test your Services, Controllers or anything else that accesses your database.

  • Generic IQueryable Repository for Entity Framework 4 (EF4)

    Tags: c#, linq, Entity Framework, EF4

    Anyone who has tried to create tests with Entity Framework (EF) knows that EF is not very unit test friendly. I needed something simple, reusable and unit testable. this generic repository was the result.

    The goal of this project was high reusability, ease of implementation and to be unit tests friendly.

    There are a lot of Repository Pattern's out there that hide a lot of the underlying functions of your data access layer (in this case LINQ). Well, I really like LINQ to SQL and didn't want to hide any of that. Plus, if you really need encapsulation it should be done in your service layer and not your repository layer.

    Some Quick Examples

    remember to add "using System.Linq"

    IRepository<Log> logs = new Repository<Log>(new MyDataContext());
    
    // use LINQ
    var items = from l in logs.All()
                where l.LogType == "Error"
                orderby l.LogId descending
                select l;
    
    // load an item
    var item = logs.All().Single(l => l.LogId == 1);
    
    // update an item
    item.TimeStamp = DateTime.Now;
    logs.Save();
    
    // create an item
    item = new Log {
        TimeStamp = DateTime.Now,
        LogType = "Information",
        Message = "This is a new Log!"
    };
    
    logs.Add(item);
    logs.Save();
    
    // delete an item
    logs.Remove(item);
    
    // Eager Loading
    items = from l in logs.All("Details")
            select l;
    
    

    Repository Code

    The code is pretty simple, it just looks long because of all the Argument Validation...

    public interface IRepository<E>
    {
        IQueryable<E> All();
        IQueryable<E> All(string includes);
        void Add(E entity);
        void Remove(E entity);
        void Update(E entity);
        void Save();
    }
    
    public class Repository<E> : IRepository<E> where E : EntityObject
    {
        protected readonly ObjectContext context;
        protected readonly ObjectSet<E> objectSet;
    
        public Repository(ObjectContext context)
        {
            #region Argument Validation
    
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
    
            #endregion
    
            this.context = context;
            this.objectSet = context.CreateObjectSet<E>();
        }
    
        public virtual IQueryable<E> All()
        {
            return objectSet;
        }
    
        public virtual IQueryable<E> All(string includes)
        {
            ObjectQuery<E> value = objectSet;
            if (String.IsNullOrEmpty(includes))
            {
                foreach (var includeProperty in includes.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    value = value.Include(includeProperty.Trim());
                }
            }
            return value;
        }
    
        public virtual void Add(E entity)
        {
            #region Argument Validation
    
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }
    
            #endregion
    
            objectSet.AddObject(entity);
        }
    
        public virtual void Remove(E entity)
        {
            #region Argument Validation
    
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }
    
            #endregion
    
            if (entity.EntityState == EntityState.Detached)
            {
                objectSet.Attach(entity);
            }
    
            objectSet.DeleteObject(entity);
        }
    
        public void Save()
        {
            context.SaveChanges();
        }
    }
    
    

    Unit Testing

    Being able to write Unit Tests is a must and was one of the main goals of creating this repository. With this class, writing unit tests has become much more simple by creating a MemoryRepository.

    public class MemoryRepository<E> : IRepository<E> where E : EntityObject
    {
        protected readonly List<E> objectSet = new List<E>();
    
        public virtual IQueryable<E> All()
        {
            return objectSet.AsQueryable();
        }
    
        public IQueryable<E> All(string includes)
        {
            return All();
        }
    
        public virtual void Add(E entity)
        {
            objectSet.Add(entity);
        }
    
        public virtual void Remove(E entity)
        {
            objectSet.Remove(entity);
        }
    
        public virtual void Update(E entity)
        {
        }
    
        public void Save()
        {
        }
    }
    
    

    Here's an example test that shows how to populate the MemoryRepository.

    [TestMethod]
    public void MemoryRepository_can_Add_entities()
    {
        // Arrange
        IRepository<Category> value = new MemoryRepository<Category>();
        value.Add(new Category { Category_ID = 1, Category_Name = "Beverages" });
        value.Add(new Category { Category_ID = 2, Category_Name = "Condiments" });
        value.Add(new Category { Category_ID = 3, Category_Name = "Confections" });
    
        // Act
        int result = value.All().Count();
    
        // Assert
        Assert.AreEqual(3, result);
    }
    

    Be sure to check out Part 2: Repository and Unit of Work for Entity Framework (EF4) for Unit Testing

  • MiniLinq for Script#

    Tags: script#, c#, javascript, linq

    Script# is my new favorite piece of technology. Write JavaScript with C#? Yes please! But since it's (currently) limited to ISO-2 C#, it can feel like you're stuck back in 2004. Using C# 2 means you're missing a lot of things you use daily... like LINQ. I do miss LINQ. So I read about Script# adding a few LINQ like extensions to the array class and decided to work them together into this MiniLinq class, which I am now sharing with you.

    Some examples

    This works with objects too, I'm just using int for simplicity.

    int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    
    // [2, 4, 6, 8, 10]
    int[] evenNumbers = (int[])MiniLinq
        .From(numbers)
        .Where(delegate(object o) { return (int)o % 2 == 0; })
        .ToArray();
    
    // [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
    int[] descendingNumbers = (int[])MiniLinq
        .From(numbers)
        .OrderBy(delegate(object x, object y) { return x == y ? 0 : (int)x > (int)y ? -1 : 1; })
        .ToArray();
    
    // [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
    int[] doubledNumbers = (int[])MiniLinq
        .From(numbers)
        .Select(delegate(object o) { return (int)o * 2; })
        .ToArray();
    
    

    I'm calling it MiniLinq because it's only a partial implementation of LINQ. To be more accurate, it's just the methods I need to use for my project. Until there's an official implementation in Script#, this is what I'll be using. If you want to download or extend MiniLinq, check it out on github. Share your changes with me!