Creating a new DbEntityEntry or mocking or simulating a DbEntityEntry

ef-code-first entity-framework

Question

I have another a question about mocking DbContext.Set question regarding simulating EF Code First in response to my previous one.

I've got a technique for my update now, and it looks like this:

if (entity == null)
    throw new ArgumentNullException("entity");

Context.GetIDbSet<T>().Attach(entity);
Context.Entry(entity).State = EntityState.Modified;
Context.CommitChanges();

return entity;

Context is my own DbContext's interface.

The issue I'm having is how to deal with the

Context.Entry(entity).State .

When I use an actual, functioning DbContext as the implementation of my Context interface, the code I've walked through works. But I'm not sure how to handle it when I insert my fictitious context there.

I am unable to just create a new instance of the DbEntityEntry class in my fictitious environment since it lacks a constructor.

Has anybody successfully faked or mocked DbEntityEntry in their CodeFirst solutions?

Or is there a more effective method to deal with state changes?

1
60
5/23/2017 11:54:51 AM

Accepted Answer

What you need to do, just as in the previous situation, is to add another degree 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;
    }
}

Consequently, you merely call instead of calling the implementationSetModified .

94
2/18/2011 12:19:32 AM

Popular Answer

I came across this query when looking for a unit testMoq no need for a custom interface. I intended to prevent modifications to certain fields, however the approachSetModified may also be used to objects.

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 Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow