huysentruitw / entity-framework-mock

Easy Mock wrapper for mocking EF6 DbContext and DbSet using Moq or NSubstitute

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Does not support binding datasources to DbSets through Set<T> method

moumtzid opened this issue · comments

Trying to bind a datasource to a DbSet through the Set method of the context like in the example below throughs an InvalidCastException with the message : "Unable to cast object of type 'System.Linq.Expressions.InstanceMethodCallExpressionN' to type 'System.Linq.Expressions.MemberExpression'."

var initialEntities = new[]
        {
            new User { Id = Guid.NewGuid(), FullName = "Eric Cartoon" },
            new User { Id = Guid.NewGuid(), FullName = "Billy Jewel" },
        };        
    var dbContextMock = new DbContextMock<TestDbContext>("fake connectionstring");
    var usersDbSetMock = dbContextMock.CreateDbSetMock(x => x.Set<User>(), initialEntities);

Can you show how your TestDbContext looks like?

CreateDbSetMock is intended to be used as:

var usersDbSetMock = dbContextMock.CreateDbSetMock(x => x.User, initialEntities);

Hi, thank you for the swift response. I understood that the intended use is with named instances of DbSets Unfortunately there are cases ( like my case where I have a generics class MyContext<T> and T actually dictates the DbSet to use ) where you have to use the Set<T>() method to get the DbSet.

I have never used DbContext like that, so please, provide an example context definition with an example of how you're using it.

public abstract class AbstractUser
{
    [Key, Column(Order = 0)]
    public virtual Guid Id { get; set; }
    public virtual string FullName { get; set; }
}
public class User : AbstractUser
{
[Required]
    [StringLength(maximumLength: 30, MinimumLength = 10)]
    public overide string FullName{ get; set; }

[Required]
    [StringLength(maximumLength: 50, MinimumLength = 10)]
    public string Address { get; set; }
}

public class TestDbContext : DbContext
{
    public TestDbContext(string connectionString)
        : base(connectionString)
    {
    }

    public virtual DbSet<User> Users { get; set; }
}

public class LimitedContext<T> where T : AbstractUser
{
    private readonly TestDbContext _context;

    public LimitedContext(TestDbContext context)
    {
        _context = context;
    }

    public void Add(T objectToAdd)
    {
        _context.Set<T>().Add(objectToAdd);
        _context.SaveChanges();
    }

    public ICollection<T> Find(string query)
    {
        return _context.Set<T>().Where(x => x.FullName.StartsWith(query)).ToList();
    }
}
  • Consider the code example above