Search code examples
entity-frameworkmoqgraphdiff

Using Moq with EntityFramework graphdiff


I have just added GraphDiff in an existing Entity Framework solution which is utilizing Moq framework for testing. All my tests that are using Moq in insert and update methods are now failing since method _context.UpdateGraph throws following exception: System.NullReferenceException: Object reference not set to an instance of an object. GraphDiff on GitHub https://github.com/refactorthis/GraphDiff

UpdateGraph extension method: https://github.com/refactorthis/GraphDiff/blob/develop/GraphDiff/GraphDiff/DbContextExtensions.cs

How should you hookup Moq with GraphDiff?


Solution

  • We had this problem as well. This is how we solved it.

    So this is in the IContext interface:

    T UpdateGraph<T>(T entity, Expression<Func<IUpdateConfiguration<T>, object>> mapping = null) where T : class, new();
    
    DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
            DbEntityEntry Entry(object entity);
    
            DbContextConfiguration Configuration { get; }
    

    This is in the base context:

     public virtual T UpdateGraph<T>(T entity, Expression<Func<IUpdateConfiguration<T>, object>> mapping = null) where T : class, new()
            {
                return null;
            }
    

    and

    private ObjectContext ObjectContext
            {
                get { return (this as IObjectContextAdapter).ObjectContext; }
            }
    

    And this is in the actual concrete context:

    public override T UpdateGraph<T>(T entity, Expression<Func<IUpdateConfiguration<T>, object>> mapping = null) // where T : class, new()
            {
                return DbContextExtensions.UpdateGraph<T>(this, entity, mapping);
            }
    

    and

    private ObjectContext ObjectContext
            {
                get { return (this as IObjectContextAdapter).ObjectContext; }
            }