I have created an n-tier solution where I am retrieving related data from a WCF service, updating it within a Windows Forms application, and then returning the updated data via WCF to be persisted to the database. The Application, WCF Service and Database are all on different machines.
The data being retrieved consists of an object and child objects...
public Product Select(string catalogueNumber) {
return (from p in this.ProductEntities.Products.Include(@"Tracks")
where p.vcCatalogueNumber == catalogueNumber
select p).FirstOrDefault() ?? new Product();
}
The updates being applied by the client application can, as well as updating existing content, also insert additional "Track" objects.
When I receive the Product object back from the client application, I can see all of the updates correctly, however in order to save all of the changes correctly I have to jump through a few hoops...
public void Save(Product product) {
Product original = this.Select(product.vcCatalogueNumber);
if (original.EntityKey != null) {
this.ProductEntities.ApplyPropertyChanges(product.EntityKey.EntitySetName, product);
// There must be a better way to sort out the child objects...
foreach (Track track in product.Tracks.ToList()) {
if (track.EntityKey == null) {
original.Tracks.Add(track);
}
else {
this.ProductEntities.ApplyPropertyChanges(track.EntityKey.EntitySetName, track);
}
}
}
else {
this.ProductEntities.AddToProducts(product);
}
this.ProductEntities.SaveChanges();
}
Surely, there has to be an easier way to do this?
Note: I have spent the better part of the afternoon investigating the EntityBag project, but found that this has not been updated to work with EF RTM. In particular, whilst it will successfully update the existing data exceptions are thrown when mixing in new objects.