Convert IQueryable <T> to DbSet <T>

I'm not sure if this is possible, but I'm trying to use the unit test repository that uses DbSet. I thought the easiest solution would be to make Enumerable and replace DbSet with this, this is my attempt.

I use C #, EntityFramework, XUnit and Moq

[Fact] public void SomeTest() { //arrange var mockContext = new Mock<MyDbContext>(); var mockData = new List<Person> { new Person { Name = "Jim", Age = 47 } }; mockContext.Setup(db => db.Persons).Returns((DbSet<Person>)mockData.AsQueryable()); var repo = PersonRepository(mockContext.Object); //act var result = repo.GetByFirstName("Jim"); //assert //do some assertion } 

The error caused by the fact that it cannot convert the EnumerableQuery type in DbSet to the mockContext.Returns statement.

Here's something similar to how the interfaces look.

PersonRepository.cs

 public class PersonRepository: EFRepository<Person>, IPersonRepository { public PersonRepository(DbContext dbContext) : base(dbContext) { } public IQueryable<Link> GetByFirstName(string name) { return DbSet.Where(p => p.FirstName == name); } } 

IPersonRepository.cs

 public interface IPersonRepository: IRepository<Person> { IQueryable<Person> GetByFirstName(string name); } 

IRepository.cs

 public interface IRepository<T> where T : class { IQueryable<T> GetAll(); T GetById(int id); void Add(T entity); void Delete(T entity); void Delete(int id); void Update(T entity); } 

EFRepository.cs

 public class EFRepository<T> : IRepository<T> where T : class { protected DbContext DbContext { get; set; } public IDbSet<T> DbSet { get; set; } public EFRepository(DbContext dbContext) { if (dbContext == null) throw new ArgumentNullException("dbContext"); DbContext = dbContext; DbSet = DbContext.Set<T>(); } ... } 
+6
source share
1 answer

What you can do is move the Linq expression from your repository to business logic and shout out the repository instead.

 public interface IPersonRepository : IRepository<Person> { IQueryable<Person> GetAll { get; } } public class PersonRepository : EFRepository<Person>, IPersonRepository { // ... public IQueryable<Person> GetAll { get { return DbSet; } } } public class SomeBusinessLogicClass { private readonly IPersonRepository _people; public SomeBusinessLogicClass(IPersonRepository people) { _people = people; } public IEnumerable<Person> GetByFirstName(string name) { return _people.GetAll.Where(p => p.FirstName == name); } } 

Now rewrite your test to test your business logic.

 [Fact] public void SomeTest() { //arrange var mockRepository = new Mock<IPersonRepository>(); var mockData = new List<Person> { new Person { Name = "Jim", Age = 47 } }; mockRepository.Setup(x => x.GetAll).Returns(mockData); var bl = new SomeBusinessLogicClass(mockRepository.Object); //act var result = bl.GetByFirstName("Jim"); //assert //do some assertion } 
+1
source

Source: https://habr.com/ru/post/953451/


All Articles