1

I am migrating a project from Linq-to-SQL to Entity Framework with POCO's, and I'm not sure how should I be creating new objects now in EF.

On the surface DbSet<T>.Create(), which creates a dynamic proxy, looks like the better way because it helps me with two-way binding automatically (If I build my POCO's correctly), but from what I saw while browsing open source projects, most just use the standard ctor new T().

The only con I can think of in using DbSet<T>.Create() is that it makes my code somewhat coupled to EF.

Is there anything else that I am missing?

Which way will help me in creating a testable, robust software more easily?

Gideon
  • 113
  • 9

1 Answers1

1

You probably need to think about abstracting the EF code away from the rest of your non-EF code, so you can replace it as needed in order to do your testing.

One of the ways (and the way I do it) is to use a generic repository:

public interface IGenericRepository<TContext, TEntity>
    where TEntity : class, IEntity
    where TContext : IDbContext
{
    TEntity NewEntity();

}

public class GenericRepository<TContext, TEntity> : IGenericRepository<TContext, TEntity> 
    where TEntity : class, IEntity 
    where TContext : IDbContext
{
    private readonly IDbContext _context;

    public GenericRepository(IUnitOfWork<TContext> uow)
    {
        _context = uow.Context;
    }

    public TEntity NewEntity()
    {
        var t = _context.Set<TEntity>().Create();
        _context.Set<TEntity>().Add(t);
        return t;
    }
}

Note that I have only included the code which directly covers your question - creating a new entity from the DBSet but also hiding the underlying method so you can easily reimplement it in a non-EF fashion.

You may get a few replies or comments about the use of generic repositories, how they are bad etc - its all opinions rather than facts, investigate the various arguments for and against and come to your own conclusions rather than be brown beaten by other people. I use them to hide the underlying persistence layer (EF, ADO.Net etc), making it easy to push a testing implementation to code further up in the chain if I need to.

  • This indeed solves that coupling issue, but from what I saw on large open source projects that are using this repository pattern, they are still creating new objects with the default ctor. Do you have any insights about the actual creation? – Gideon Jun 12 '14 at 09:59
  • I'm assuming you want to do something like `_context.Set().Create("value1", "value2", "value3")`, in the same manner as object initialisers? Then I'm afraid that isn't currently supported in EF I'm afraid. You could do a whole load of things with reflection etc but I doubt it would be worth it. –  Jun 12 '14 at 10:10