Peter Bons
Peter Bons

Reputation: 29840

Force reload navigation property from database

I have a problem with refreshing the data from the database. See the code below. What I try to accomplish here is this: I create a ProductProtocol (p) and add one ProductProtocolContent to the list of ProductProtocolContents. Then I save the whole lot to the database. After that I simulate a change I make (the addition of another ProductProtocolContent ) that I want to undo and I want to test that after refreshing the object using my repository the

var p = new ProductProtocol { Name = "test1" };

p.ProtocolContents.Add(new ProductProtocolContent { ValidFrom = DateTime.Now, Value = "9_qwe2341" });

var r = RepositoryFactory.Create<ProductProtocol>(unitOfWork);
r.Add(p);
unitOfWork.Commit();

// add another ProductProtocolContent, p.ProductProtocolContents.Count == 2
p.ProtocolContents.Add(new ProductProtocolContent { ValidFrom = DateTime.Now, Value = "9_truf7461" });

// undo the changes to the object
r.Refresh(p);

// reload the ProductProtocolContents from the database
r.LoadPropertySet(p, pc => pc.ProtocolContents);

// p.ProductProtocolContents.Count should be 1
Assert.IsTrue(p.ProtocolContents.Count == 1);

My problem is that p.ProtocolContents.Count == 0 at the time Assert.IsTrue is called.

The implementation of r.LoadPropertySet() is as follows:

public void LoadPropertySet<Y>(T target, Expression<Func<T, ICollection<Y>>> spec) where Y : BaseBusinessObject
{
    context.Entry(target).Collection(spec).CurrentValue.Clear();
    context.Entry(target).Collection(spec).Load();
}

using Entity Framework 4 (using the ObjectContext instead of DbContext)I simply did this and that worked:

context.LoadProperty(target, spec, MergeOption.OverwriteChanges);

How would I do this using the DbSet, Must I convert back to ObjectContext or is there a equivalent for DbSet?

Upvotes: 2

Views: 2424

Answers (1)

L-Four
L-Four

Reputation: 13551

If you can't do it on DBContext, you can always cast to ObjectContext and use its functionality.

MSDN: DbContext wraps ObjectContext and exposes the most commonly used features of ObjectContext by using simplified and more intuitive APIs. You can access the underlying ObjectContext whenever you need to use features that are not supported by DbContext.

Upvotes: 1

Related Questions