I am using entity framework 4, WCF and Silverlight.
I have a many to many relationship of Order to Products.
[Order]*--*[Product]
Using Model first, Entity Framework automatically creates the join table for me. When I create everything on the server side, things work ok. The problem comes when using Silverlight.
I bring back the list of products and display them on the screen. The user creates a new Order, and selects the Products that should be apart of the order. Then it is submitted to WCF.
var order = new order();
order.CustomerName = customerTextBox.Text;
...
order.Products = new ObservableCollection<Product>();
foreach (var product in selectedProducts)
{
order.Products.Add(product);
}
var proxy = new OrderService();
proxy.CreateOrderAsync(order);
On the server side, it is just a very simple add method
var db = new Model1Container();
db.Products.AddObject(order);
db.SaveChanges();
However something strange happens. When this is saved, almost everything in the database gets duplicated a few times. My guess would be because Entity Framework is traversing the cyclic links a few times.
I tried changing it to db.Categories.Attatch(order). But this resulted in nothing being saved. I also tried looping and manually attaching each of the products before saving the order. But this results in an exception being thrown, stating that objects have already been attached to the context.
Edit: Doing this stops Products being duplicated. But all the Orders in the table are still duplicated. Must be traversing all the relationships still?
db.Orders.AddObject(order);
db.ObjectStateManager.ChangeObjectState(order, EntityState.Added);
foreach (var product in order.Products)
{
db.ObjectStateManager.ChangeObjectState(product, EntityState.Unchanged);
}
db.SaveChanges();