0

I have a nice clean domain layer in my app that was developed in a DDD fashion. The database was not considered at all when developing the domain. Property names make sense, aren't in ALL CAPS, and are relevant to my application.

Today, I am implementing a repository to pull from an existing EF DbContext. The DbContext was developed to (basically) match a poorly-designed Oracle database.

Ideally, I would like to implement a repository like this:

public interface IRepository {
    IQueryable<T> Find<T>(Expression<Func<T, bool>> query) where T : IMyDomainEntity;
}

T is my domain entity. But, inside my Find method in my repository, I have to...

  1. Somehow convert the expression to work with the DbContext

    I am not sure how to do this yet.

  2. Query the DbContext

    Once the expression is 'mapped', this is simple

  3. Somehow map to my domain object

    I'm sure I can use AutoMapper or implement my own mapper.

  4. Return an IQueryable having not made a trip to the database yet.

    Not sure this is possible after all the meddling done in #'s 1 - 3

So, how has this problem been solved in the past? Are there any reusable patterns here?

2
  • Ditch EF and use NHibernate or RavenDb. (OMG .. did someone just suggest that?! WIN!)
    – Pure.Krome
    Jun 28, 2012 at 4:15
  • 1
    I'm with you, but the company is not. The closest thing I can do is ditch the company. Jun 28, 2012 at 15:52

1 Answer 1

0

Well, you're on the right track already, just implement what your say you want :)

1.You're passing an expression into your find method so, just use that expression in your Where clause

2.You just need to get the correct DbSet from your DbContext to query against, DbContext has a method to get the DbContext of a given type, use that and you can query like

public IQueryable<T> Find<T>(Expression<Func<T, bool>> query) where T : IMyDomainEntity
{
   var dbSet = context.Set<T>();
   return dbSet.Where(query);
}

3.If your domain objects are not the ones mapped by EF to the database, you'll need to customize your mapping against what's in your DB in your DbContext class (no need for automapper for that), so you would have something like this in your DbContext class

public class MyContext : DbContext 
{
   ...
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>()
                .Map(a => a.ToTable("DB_USERS"))
                .Property(a => a.Email).HasColumnName("MAIL");

            base.OnModelCreating(modelBuilder);
        }
}

To map from the table DB_USERS in the DB to the class User, having different names for the fields, etc. here's an article on that

http://www.codeproject.com/Articles/165720/Using-the-Code-First-Model-Configuration-Classes

You could also map the properties to the correct table columns using attributes if you don't want/can't change your DbContext class

http://msdn.microsoft.com/en-us/data/gg193958

Or you can have a different set of entities that are mapped to your DB and use automapper to translate them into your domain objects, but you lose no. 4 bellos since you'll need to materialize the query to automap it to your domain model.

4.No need to do anything special, EF takes care of the that

UPDATE: Solution without having access to the DbContext (not fully generic version but works)

The idea is to create the mapping part of the repository for each domain class, so all gets binded correctly. Continueing with the User domain model and DBUser table model:

public class User : IDomainModelEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

public class DBUser
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int USER_ID { get; set; }

    [Required]
    [MaxLength(150)]
    public string USER_NAME { get; set; }

    [Required]
    [MaxLength(260)]
    public string USER_MAIL { get; set; }
}

Then you would have an abstract Repository and an a concrete repository per domain class that implements the basic GetAll query mapped:

public abstract class Repository<T>  where T : IDomainModelEntity
{
    protected readonly DbContext _context;

    public Repository(DbContext context)
    {
        _context = context;
    }

    public abstract IQueryable<T> GetAll();

    public IQueryable<T> Find(Expression<Func<T, bool>> predicate)
    {
        return GetAll().Where(predicate);
    }

}

public class UserRepository : Repository<User>
{
    public UserRepository(DbContext context)
        : base(context)
    {
    }

    public override IQueryable<User> GetAll()
    {
        return _context.Set<DBUser>()
            .Select(u => new User
                {
                    Id = u.USER_ID,
                    Name = u.USER_NAME,
                    Email = u.USER_MAIL
                });
    }
}

now to use it you will just call the find or get all on the repository...

        using (var context = new CompanyDbContext())
        {
            var repo = new UserRepository(context);
            var list = repo.Find(a=>a.Id >= 2).ToList();

            list.ForEach(a => Console.WriteLine("Id: {0}, Name {1}, email {2}", a.Id, a.Name, a.Email));
        }

It is not fully generic since you will need to pass a repository for each domain class you need to use, but it may be an acceptable compromise

Hope this helps

5
  • context.Set<T> doesn't exist because T is IMydomainEvent and my domain events don't exist in the DbContext. My domain entities and the EF entities are different object types. Jun 28, 2012 at 2:25
  • I have been handed an existing EF DbContext. I can't change it. I have to deal with it as it is. Jun 28, 2012 at 3:42
  • Can't you just create a new dbcontext that does the mapping correctly? and not use the one your're give?
    – Jaime
    Jun 28, 2012 at 3:57
  • Not allowed. The company wants to have one DbContext for all tables in the database at hand. If I could create my own DbContext, I wouldn't be here asking this question... it'd be easy. Jun 28, 2012 at 4:09
  • Then I'm not sure the one-generic-repo for everything can work, since T (the generic param) has to be resolved at compile time and you want to map from your domain model to the db tables model at runtime... One way to go arround that would be to implement one repo per domain class that does the mapping at compile time.
    – Jaime
    Jun 28, 2012 at 15:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.