Note that there are some explanatory texts on larger screens.

plurals
  1. POConverting an IQueryable<T> to a DbSet<T>
    primarykey
    data
    text
    <p>I'm not sure that this is possible, but I'm trying to unit test a repository that uses a DbSet. I thought the easiest solution would just be to make an Enumerable, and replace the DbSet with that, this is my attempt.</p> <p>I'm using C#, EntityFramework, XUnit, and Moq</p> <pre><code>[Fact] public void SomeTest() { //arrange var mockContext = new Mock&lt;MyDbContext&gt;(); var mockData = new List&lt;Person&gt; { new Person { Name = "Jim", Age = 47 } }; mockContext.Setup(db =&gt; db.Persons).Returns((DbSet&lt;Person&gt;)mockData.AsQueryable()); var repo = PersonRepository(mockContext.Object); //act var result = repo.GetByFirstName("Jim"); //assert //do some assertion } </code></pre> <p>The error that gets thrown is it can't convert type EnumerableQuery to a DbSet on the mockContext.Returns statement.</p> <p>Here is something similar to what the interfaces look like.</p> <p><strong>PersonRepository.cs</strong></p> <pre><code>public class PersonRepository: EFRepository&lt;Person&gt;, IPersonRepository { public PersonRepository(DbContext dbContext) : base(dbContext) { } public IQueryable&lt;Link&gt; GetByFirstName(string name) { return DbSet.Where(p =&gt; p.FirstName == name); } } </code></pre> <p><strong>IPersonRepository.cs</strong></p> <pre><code>public interface IPersonRepository: IRepository&lt;Person&gt; { IQueryable&lt;Person&gt; GetByFirstName(string name); } </code></pre> <p><strong>IRepository.cs</strong></p> <pre><code>public interface IRepository&lt;T&gt; where T : class { IQueryable&lt;T&gt; GetAll(); T GetById(int id); void Add(T entity); void Delete(T entity); void Delete(int id); void Update(T entity); } </code></pre> <p><strong>EFRepository.cs</strong></p> <pre><code>public class EFRepository&lt;T&gt; : IRepository&lt;T&gt; where T : class { protected DbContext DbContext { get; set; } public IDbSet&lt;T&gt; DbSet { get; set; } public EFRepository(DbContext dbContext) { if (dbContext == null) throw new ArgumentNullException("dbContext"); DbContext = dbContext; DbSet = DbContext.Set&lt;T&gt;(); } ... } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload