We're using EF Code first, and have a data context for our sales database. Additionally, we have a class that sits on top of our data context and does some basic CRUD operations.
For example, we have the following function:
public static T Create<T>(int userId, T entity) where T : class, IAllowCreate
{
if (entity == null)
throw new ArgumentNullException("entity");
using (SalesContext dc = new SalesContext())
{
dc.Set<T>().Add(entity);
dc.SaveChanges();
return entity;
}
}
I found an example of how to create fake contexts and IDBset properties. I started implementing that, but I ran in to an issue.
We use dc.Set() quite liberally (as seen above) in our code, as we attempt to create generic CRUD methods. Instead of having a ReadCustomer, ReadContact etc, we would just do Read(). However, dc.Set returns a DbSet, not an IDbSet, so I'm not able to mock that.
Has anyone been able to mock or fake DbContext and still use the Set functionality?
interface ISalesContext
{
IDbSet<T> GetIDbSet<T>();
}
class SalesContext : DbContext, ISalesContext
{
public IDbSet<T> GetIDbSet<T>()
{
return Set<T>();
}
}
I used a different name, but you can use the new
operator if you prefer to hide the regular implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With