Mocking or faking DbEntityEntry or creating a new DbEntityEntry - entity-framework

Following on the heels of my other question about mocking DbContext.Set I've got another question about mocking EF Code First.
I now have a method for my update that looks like:
if (entity == null)
throw new ArgumentNullException("entity");
Context.GetIDbSet<T>().Attach(entity);
Context.Entry(entity).State = EntityState.Modified;
Context.CommitChanges();
return entity;
Context is an interface of my own DbContext.
The problem I'm running in to is, how do I handle the
Context.Entry(entity).State.
I've stepped through this code and it works when I have a real live DbContext as the implementation of my Context interface. But when I put my fake context there, I don't know how to handle it.
There is no constructor for a DbEntityEntry class, so I can't just create a new one in my fake context.
Has anyone had any success with either mocking or faking DbEntityEntry in your CodeFirst solutions?
Or is there a better way to handle the state changes?

Just like the other case, what you need is to add an additional level of indirection:
interface ISalesContext
{
IDbSet<T> GetIDbSet<T>();
void SetModified(object entity)
}
class SalesContext : DbContext, ISalesContext
{
public IDbSet<T> GetIDbSet<T>()
{
return Set<T>();
}
public void SetModified(object entity)
{
Entry(entity).State = EntityState.Modified;
}
}
So, instead of calling the implementation, you just call SetModified.

Found this question when I needed to unit test with Moq, no need for your own interface. I wanted to set specific fields to not modified but the method SetModified can be used with object as well.
DbContext:
public class AppDbContext : DbContext
{
...
public virtual void SetModified(GuidEntityBase entity)
{
Entry(entity).State = EntityState.Modified;
Entry(entity).Property(x => x.CreatedDate).IsModified = false;
Entry(entity).Property(x => x.CreatedBy).IsModified = false;
}
...
}
Test:
var mockContext = new Mock<AppDbContext>();
mockContext.Setup(c => c.MyDbSet).Returns(mockMyDbSet.Object);
mockContext.Setup(c => c.SetModified(It.IsAny<GuidEntityBase>()));

Related

Shim DbContext ctor for Effort unit testing

I'd like to intercept var context = new MyDbContext() to return a different constructor call instead.
The great thing about EFfort is that it let's you set up an easy in-memory database for unit testing.
var connection = Effort.DbConnectionFactory.CreateTransient();
var testContext = new MyDbContext(connection);
But then you'd have to inject that context into your repository.
public FooRepository(MyDbContext context) { _context = context; }
Is it possible to just intercept var context = new MyDbContext() , so that it returns the testContext?
using (var context = new MyDbContext()) {
// this way, my code isn't polluted with a ctor just for testing
}
You have two possible options. Using factories or via Aspect oriented programming (like PostSharp)
referencing this article: http://www.progware.org/Blog/post/Interception-and-Interceptors-in-C-(Aspect-oriented-programming).aspx
Using PostSharp (AOP)
PostSharp is a great tool and can achieve the most clean interception
possible (meaning no changes in your classes and object generation at
all even if you do not your factories for object creation and/or
interfaces) but it is not a free library. Rather than creating proxies
at runtime, it injects code at compile time and therefore changes your
initial program in a seamless way to add method interception.
.....
The cool thing in this is that you do not change anything else in your
code, so your object can be still generated using the new keyword.
Using DI and Factory-pattern
I personally prefer the factory-pattern approach, but you seem apposed to having to inject any dependencies into your classes.
public interface IDbContextFactory<T> where T : DbContext {
T Create();
}
public class TestDbContextFactory : IDbContextFactory<MyDbContext> {
public MyDbContext Create() {
var connection = Effort.DbConnectionFactory.CreateTransient();
var testContext = new MyDbContext(connection);
return testContext;
}
}
public class FooRepository {
MyDbContext _context;
public FooRepository(IDbContextFactory<MyDbContext> factory) {
_context = factory.Create();
}
}
(edit: I just realized this isn't actually returning the other ctor call. working on it.)
Figured it out. Simple enough if you know how to do it:
[TestMethod]
public void Should_have_a_name_like_this()
{
// Arrange
var connection = Effort.DbConnectionFactory.CreateTransient();
ShimSolrDbContext.Constructor = context => new SolrDbContext(connection);
// Act
// Assert
}
And as usual, EFfort requires this constructor in the DbContext class:
public class SomeDbContext
{
public SomeDbContext() : base("name=Prod")
{
}
// EFfort unit testing ctor
public SomeDbContext(DbConnection connection) : base(connection, contextOwnsConnection: true) {
Database.SetInitializer<SolrDbContext>(null);
}
}
But it means the repo is blissfully unaware of the special Transient connection:
public class SomeRepository
{
public void SomeMethodName()
{
using (var context = new SomeDbContext())
{
// self-contained in repository, no special params
// and still calls the special test constructor
}
}
}

Disposing of object context when implementing a repository (DAL) and Mocking DAL for TDD

I am running into an issue where I can't figure out how to properly dispose of my object context I am creating every time I instantiate a new object.
public class OrderBLL{
var _iOrderLineDal;
public OrderBLL(){
_iOderLineDal = new OrderLineDal(new entityOBject(dbconnectionstring);
}
public OrderBLL(iOrderLineDal mockOrderLineDal){
_iOrderLineDal = mockOrderLineDal;
}
}
So the problem is, that every 30 seconds my service creates a new instance of the OrderBLL and then runs a method to see if there are any new orders in the Data base.
So every 30 seconds I create a new entityObject that is not being disposed of. the old implementation of the code was written using the using statement.
public bool HasNewOrders(){
using(var entityObject = new entityObject(dbconnectionString)){
var newOrders = entityObject.GetNewOrders();
}
//some logic
}
The problem with using this using statement is I cannot mock out the entityObject and easily write unit tests on any methods inside this OrderBLL class.
I tried disposing of it with a dispose method inside the OrderLineDal and once i got the data called dispose. That worked well the first iteration but the following iterations, the next 30 seconds, it would say that the entityObject was disposed of and cannot be used. (doesn't make sense to me, since I am creating a new one every time?)
Is there a way I can implement this repository pattern and still dispose of all the new entityObjects so I can mock the DAL out for unit testing?
I am working with EF 4. and it was not set up Code First, so I do not have POCO.
Ideally you would want to create your context outside of your OrderBLL (search google for Repository pattern).
public class OrderRepository : IOrderRepository, IDisposable
{
private readonly IOrderDBContext _dbContext;
// poor mans dependency injection
public OrderRepository() : this(new OrderDbContext("YourConnectionString")
{}
public OrderRepository(IOrderDBContext dbContext)
{
if (dbContext == null) throw new ArgumentNullException("dbContext");
_dbContext = dbContext;
}
public bool GetNewOrders(){
return _dbContext.Orders.Where(o => o.IsNew==true);
}
public void Dispose()
{
if (_dbContext != null) _dbContext.dispose();
}
}
public class OrderBLL : IOrderBLL
{
private readonly IOrderRepository _repository;
public OrderRepository(IOrderRepository repository)
{
if (repository == null) throw new ArgumentNullException("dbContext");
_repository = repository;
}
public bool HasNewOrders(){
var newOrders = _repository.GetNewOrders();
if (newOrders==null) return false;
return newOrders.Count() > 0;
}
}
[Test]
public void HasNewOrders_GivenNoNNewOrdersRetunedFromRepo_ReturnsFalse()
{
// test using nunit and nsubstitute
// Arrange
var repository = Substitue.For<IOrderRepository>();
var emptyOrderList = new List<Order>();
repository.GetNewOrders().Returns();
var orderBLL = new OrderBLL(repository);
// Act
var result = orderBLL.HasNewOrders();
// Assert
Assert.Equals(false, result);
}
Now you can inject your context into this class and easily test your business logic. Eventually you will need to create your dbContext and should also always expose this. I would suggest having a look at a DI container like Castle Windsor to manage the life of your objects, although in a service you may just want to manually create and dispose your context as close to the code entry point as possible (e.g. in the main method)

Disposing entity framework dbcontext in singleton class (StructureMap)

In my application i am using StructureMap with EntityFramework.
Well, my ioc config looks like :
x.For<IDbContext>().Use(c => new DbContext(AppSettings.ConnectionString));
x.For<IManager>().Singleton().Use<DefaultManagerImplementation);
x.For<IManagerService>().Use<DefaultManagerServiceImplementation>();
My problem is about disposing DbContext instance, which one is use in IManagerService.
IManagerService :
using(var ctx = new DbContext(AppSettings.ConnectionString)
{
// works fine
ctx.
ctx.save();
}
public class ManagerService : IManagerService
{
private readonly IDbContext _dbContext;
public ManagerService(IDbcontext dbContext)
{
// not works, because DbContext is not disposed?
_dbContext = dbContext; // inject
...
_dbContext.Get... return old data
}
}
Well, is here any change to force dispose object which lives in singleton instance in structure map?
Thanks
You won't get any automatic disposing of this object because as far as your container is concerned, you're still using it. There are two options here:
Explicitly call .Dispose() on the DbContext when you're finished with it. You won't be able to use the DbContext anywhere else within your Singleton, since the object is now gone.
Instead of taking a dependency on DbContext, take a dependency on Func<DbContext> (or some other factory interface). I'm not sure about StructureMap, but other IoC containers handle Func automatically as long as you've registered T, so this shouldn't need any new dependencies. This would change your constructor to the following:
public class ManagerService : IManagerService
{
private readonly Func<IDbContext> _dbContextFactory;
public ManagerService(Func<IDbContext> dbContextFactory)
{
_dbContextFactory = dbContextFactory; // inject
using (var context = _dbContextFactory())
{
...
// Do stuff with your context here
} // It will be disposed of here
using (var context = _dbContextFactory())
{
// ...and here's another context for you
}
}
}

Code first DbContext usage

I have been trying to work with Entity Framework's Code First. I wrote the below line of code
DbContext _context = new DbContext(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
However on execution, the connection remains closed. Is there something wrong with this code??
I have created a generic repository class using the DBContext shown below
public class GenericRepository<T> where T:class
{
public DbContext _context = new DbContext(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
private DbSet<T> _dbset;
public DbSet<T> Dbset
{
set { _dbset = _context.Set<T>(); }
get { return _dbset; }
}
public IQueryable<T> GetAll()
{
return Dbset;
}
}
and I then call this class on the page load event, where Teacher is an entity class which maps to a table in the database
protected void Page_Load(object sender, EventArgs e)
{
GenericRepository<Teacher> studentrepository = new GenericRepository<Teacher>();
rptSchoolData.DataSource = studentrepository.GetAll().ToList();
rptSchoolData.DataBind();
}
but the connection remains closed and there is also an InvalidOperation Exception in the ServerVersion of the context object.
Am I missing something??
This property
public DbSet<T> Dbset
{
set { _dbset = _context.Set<T>(); }
get { return _dbset; }
}
has a heavy smell to it. A setter that does nothing with value is an anti pattern big time. Do you expect to set the DbSet after creating a GenericRepository?
I don't understand that your code even works because you never initialize _dbset, it should throw a null object reference exception.
The _dbset and DbSet shouldn't be there in the first place. GetAll should return _context.Set<T>(). EF should open and close the connection all by itself. Maybe the fact that you don't initialize the DbSet causes a connection never to open, causing problems in other pieces of code not revealed here.

Multiple telerik MVC grids in TabStrip not working with ninject and entity framework, unit of work, repository pattern

I am creating an ASP.NET MVC 3 e-commerce website and I am currently working on the admin area where you can add/edit products. To create the UI for the product page I am using Telerik MVC controls.
My problem is that when I added a second telerik grid which both retrieve data from the database through an ajax call I receive a couple different errors listed below:
{"There is already an open DataReader associated with this Command
which must be closed first."}
{"The connection was not closed. The connection's current state is
connecting."}
Database Context Code
public interface IUnitOfWork
{
void Commit();
}
public class GSPDataContext : DbContext, IUnitOfWork
{
/* (omitted) IDbSet's for entities */
public GSPDataContext()
: base("GSPConnectionString")
{
}
public virtual IDbSet<T> DbSet<T>() where T : class
{
return Set<T>();
}
public virtual void Commit()
{
base.SaveChanges();
}
}
Generic Repository Code
public class Repository<T> : IRepository<T> where T : class
{
private GSPDataContext m_dataContext;
private readonly IDbSet<T> m_entity;
public Repository(GSPDataContext dataContext)
{
if (dataContext == null)
throw new ArgumentException();
m_dataContext = dataContext;
m_entity = m_dataContext.Set<T>();
}
public T GetById(int id)
{
return this.m_entity.Find(id);
}
public void Insert(T entity)
{
if (entity == null)
throw new ArgumentException();
this.m_entity.Add(entity);
//this.m_dataContext.SaveChanges();
}
public void Delete(T entity)
{
if (entity == null)
throw new ArgumentException();
this.m_entity.Remove(entity);
//this.m_dataContext.SaveChanges();
}
public virtual IQueryable<T> Table
{
get
{
return this.m_entity;
}
}
}
Ninject Code
private static void RegisterServices(IKernel kernel)
{
//Customer
kernel.Bind<IAddressValidationService>().To<AddressValidationService>().InRequestScope();
kernel.Bind<ICustomerService>().To<CustomerService>().InRequestScope();
kernel.Bind<ICustomerProductService>().To<CustomerProductService>().InRequestScope();
//Authentication
kernel.Bind<IOpenIDLoginService>().To<OpenIDLoginService>().InRequestScope();
kernel.Bind<IAuthenticationService>().To<FormsAuthenticationService>().InRequestScope();
//Products
kernel.Bind<IProductService>().To<ProductService>().InRequestScope();
kernel.Bind<IRecentlyViewedProductService>().To<RecentlyViewedProductService>().InRequestScope();
kernel.Bind<IProductPictureService>().To<ProductPictureService>().InRequestScope();
kernel.Bind<ICategoryService>().To<CategoryService>().InRequestScope();
kernel.Bind<IPictureService>().To<PictureService>().InRequestScope();
//Shopping Cart
kernel.Bind<IShoppingCartService>().To<ShoppingCartService>().InRequestScope();
//Shipping and Payment
kernel.Bind<IShippingService>().To<ShippingService>().InRequestScope();
kernel.Bind<IPaymentService>().To<PaymentService>().InRequestScope();
//Orders
kernel.Bind<IOrderCalculationService>().To<OrderCalculationService>().InRequestScope();
kernel.Bind<IOrderProcessingService>().To<OrderProcessingService>().InRequestScope();
kernel.Bind<IOrderService>().To<OrderService>().InRequestScope();
//
kernel.Bind<IEncryptionService>().To<EncryptionService>().InRequestScope();
kernel.Bind<ILogger>().To<LoggingService>().InRequestScope();
kernel.Bind<IWebManager>().To<WebManager>().InRequestScope();
//Messages
kernel.Bind<IEmailService>().To<EmailService>().InRequestScope();
kernel.Bind<IMessageTemplateService>().To<MessageTemplateService>().InRequestScope();
kernel.Bind<IWorkflowMessageService>().To<WorkflowMessageService>().InRequestScope();
//Data
kernel.Bind<GSPDataContext>().ToSelf().InSingletonScope();
kernel.Bind<IUnitOfWork>().ToMethod(ctx => ctx.Kernel.Get<GSPDataContext>()).InSingletonScope();
kernel.Bind(typeof (IRepository<>)).To(typeof (Repository<>)).InRequestScope();
kernel.Bind<IWorkContext>().To<WebWorkContext>().InRequestScope();
}
I suspect it has something to do with how ninject is managing the lifetimes of the various services, but I am not sure what I need to do to make it work.
Any advice would be much appreciated.
Thanks
UPDATE
According to Remo's comment I change my code to the following:
//Data
kernel.Bind<GSPDataContext>().ToSelf().InRequestScope();
kernel.Bind<IUnitOfWork>().ToMethod(ctx => ctx.Kernel.Get<GSPDataContext>()).InRequestScope();
kernel.Bind(typeof (IRepository<>)).To(typeof (Repository<>)).InRequestScope();
And I am now getting the following error:
The ObjectContext instance has been disposed and can no longer be used
for operations that require a connection.
Any ideas?
No, it has nothing to do with how Ninject manages lifetimes. But it has to do how you configured the lifecycles.
It is important that a new DbContext is used for each request. This has to be InRequestScope.