title: Entity Framework 6 and Moq4: Is it possible to have a mocked DbSet retain added data for the duration of its scope?
body: <p>Background:
   - Using EntityFramework 6
   - Using Moq v4.2.1402.2112
   - Using DbFirst methodology</p>
  
  <p>I have been following the EF6 Moq walkthrough (which can be found <a href="http://msdn.microsoft.com/en-gb/data/dn314429.aspx" rel="nofollow">here</a>) however; I have been wondering if it is possible to have a mocked DbSet retain the data that is added to it for the duration of it's scope?</p>
  
  <p>For example:</p>
  
  <pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting; 
  using Moq; 
  using System.Collections.Generic; 
  using System.Data.Entity; 
  using System.Linq; 
  
  namespace TestingDemo 
  { 
      [TestClass] 
      public class QueryTests 
      { 
          [TestMethod] 
          public void GetAllBlogs_orders_by_name() 
          { 
              var data = new List&lt;Blog&gt; 
              { 
                  new Blog { Name = "BBB" }, 
                  new Blog { Name = "ZZZ" }, 
                  new Blog { Name = "AAA" }, 
              }.AsQueryable(); 
  
              var mockSet = new Mock&lt;DbSet&lt;Blog&gt;&gt;(); 
              mockSet.As&lt;IQueryable&lt;Blog&gt;&gt;().Setup(m =&gt; m.Provider).Returns(data.Provider); 
              mockSet.As&lt;IQueryable&lt;Blog&gt;&gt;().Setup(m =&gt; m.Expression).Returns(data.Expression); 
              mockSet.As&lt;IQueryable&lt;Blog&gt;&gt;().Setup(m =&gt; m.ElementType).Returns(data.ElementType); 
              mockSet.As&lt;IQueryable&lt;Blog&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(data.GetEnumerator()); 
  
              var mockContext = new Mock&lt;BloggingContext&gt;(); 
              mockContext.Setup(c =&gt; c.Blogs).Returns(mockSet.Object); 
  
              var service = new BlogService(mockContext.Object);
              service.AddBlog("YYY", "http://blogs.msdn.com/yyyy"); 
              var blogs = service.GetAllBlogs(); 
  
              Assert.AreEqual(4, blogs.Count);    // Fails because whilst the AddBlog is called, and we can verify this, the AsQueryable List doesn't retain the new data
              Assert.AreEqual("AAA", blogs[0].Name); 
              Assert.AreEqual("BBB", blogs[1].Name); 
              Assert.AreEqual("YYY", blogs[2].Name); 
              Assert.AreEqual("ZZZ", blogs[3].Name); 
          } 
      } 
  }
  </code></pre>
  
  <p>Is it possible to have the added data retained so it can be queried later in the test?</p>