EntityFramework 6 - sample async repository

Intro

EntityFramework 6 introduced support for async /await. You can read more about Asynchronous Programming with Async and Await on the following link: http://msdn.microsoft.com/en-us/library/hh191443.aspx

Implementation

First, let's create a Person class:

public class Person
{
    public int PersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

then let's define our DbContext:

public class MyDbContext : DbContext
{
    public MyDbContext() : base("MyConnectionStringName")
    {
    }

    public DbSet<Person> People { get; set; }
}

and let's define an interface:

public interface IPersonRepository
{
    Task<Person> GetByIdAsync(int id);
    Task<List<Person>> GetAsync(Expression<Func<Person, bool>> predicate);
    Task<List<Person>> GetAllAsync();
    Task InsertAsync(Person person);
    Task UpdateAsync(Person person);
    Task DeleteAsync(int id);
}

and here's our async repository:

public class PersonRepository : IPersonRepository
{
    public async Task<Person> GetByIdAsync(int id)
    {
        using (var db = new MyDbContext())
        {
            return await db.People.FirstOrDefaultAsync(x => x.PersonId == id);
        }
    }

    public async Task<List<Person>> GetAsync(Expression<Func<Person, bool>> predicate)
    {
        using (var db = new MyDbContext())
        {
            return await db.People.Where(predicate).ToListAsync();
        }
    }

    public async Task<List<Person>> GetAllAsync()
    {
        using (var db = new MyDbContext())
        {
            return await db.People.ToListAsync();
        }
    }

    public async Task InsertAsync(Person person)
    {
        using (var db = new MyDbContext())
        {
            db.People.Add(person);
            await db.SaveChangesAsync();
        }
    }

    public async Task UpdateAsync(Person person)
    {
        using (var db = new MyDbContext())
        {
            db.People.Attach(person);
            db.Entry(person).State = EntityState.Modified;
            await db.SaveChangesAsync();
        }
    }

    public async Task DeleteAsync(int id)
    {
        using (var db = new MyDbContext())
        {
            var person = new Person { PersonId = id };

            db.People.Attach(person);
            db.Entry(person).State = EntityState.Deleted;
            await db.SaveChangesAsync();
        }
    }
}
comments powered by Disqus