I have been searching for a while now and nothing I can find works. I have a situation where I have two objects (see definition below). The child object is a collection on the parent. I am working in Visual Studio 2012 with WPF/Prism and Entity Framework 4.4
class Parent
{
...other properties...
public virtual ICollection<Child> Children { get; set; }
}
class Child
{
public string Value1 { get; set }
public string Value2 { get; set }
public string Value3 { get; set }
}
I have a Form that has the Parent loading into a list box on the left hand side and the user clicks on one of the items in the list and we show the properties on the right hand side. Everything works great UNTIL we have two machines hitting the same database. if one machines adds or updates one of the records, I am having issues with the second machine getting the data...
I have the following code to try and fix it, but it seems like there should be an easy way within the entity framework.
DbEntityEntry<Parent> entry = dbContext.Entry(parent);
entry.Reload(); //Note: this refreshes the properties on the Parent object (but not the collection
if (Parent.Children != null)
{
Array a = doc.Children.ToArray<Child>(); //this is here because they may have deleted one of the records
foreach (Child g in a)
{
DbEntityEntry<Child> c= dbContext.Entry(g);
c.Reload(); //Note: if it is deleted, the Parent.Child gets updated automatically to remove the record.
}
}
entry.Collection(o => o.Children ).Load(); //call this to get new records
Any thoughts I on what I can do better or is this the way to do it?????
Moved this to an answer
found a better way to do the "foreach" above on the array
((IObjectContextAdapter)dbContext).ObjectContext.Refresh(RefreshMode.StoreWins, parent.Children);
this removes entries and updates current ones. still need the .Load() to get new records. This also seems to be a lot faster also
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