I know there is a Load
method.
_dbContext.Entry(blog).Collection(b => b.Posts).Load()
But I'm try to handle concurrency conflicts, I've been add a post
into blog.Posts
. if call Load
, it do not clear the blog.Posts
, just append the existing Posts
to it.
I had try:
blog.Posts = null;
_dbContext.Entry(blog).Collection(b => b.Posts).Load()
But blog.Posts
become a empty collection (Zero Count).
So I want a Reload
.
Unfortunately although EntityEntry
has Reload
method, there is no such method for ReferenceEntry
and CollectionEntry
(or in general, for NavigationEntry
which the base of the previous two). And Reload
methods refreshes just the primitive properties, so it can't be used to refresh the navigation properties.
Fortunately it's not that hard to create a custom one. It needs to detach (or reload?) all the current collection items, set IsLoaded
to false
and CurrentValue
to null
before calling Load
.
Something like this (put it in a static class of your choice and add the necessary using
s):
public static void Reload(this CollectionEntry source)
{
if (source.CurrentValue != null)
{
foreach (var item in source.CurrentValue)
source.EntityEntry.Context.Entry(item).State = EntityState.Detached;
source.CurrentValue = null;
}
source.IsLoaded = false;
source.Load();
}
so you can use the desired
_dbContext.Entry(blog).Collection(b => b.Posts).Reload();
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