I might be totally wrong but a simple insert and update using EF4 is driving me insane.(Novice in EF)
I have created a noddy project and uploaded here
Feel free to download if you like and fix the issue.THAT WOULD BE FANTASTIC.
In a nutshell I would like somebody to tell me that what I suspect is not the case.
Suppose you have a customer object. Do you need to fetch it first before updating like you do for delete?That seems insane to me.
Given that you have a save method(both insert and update are done here)and you pass you customer to it.You already have all the details .How would you modify to make it work? I get all sorts of errors. do I need to go to the db each time I need to modify a child of my customer?
public void Save(CustomerDTO customerDTO)
{
//convert dto to EF entity
var entityCustomer=ToEntityCustomer(customerDTO)
using(ctx=new CustomerContext())
{
if(efCustomer.CustomerId > 0)
{
//UPDATE
//DO I NEED TO FETCH MY CUSTOMER AGAIN FROM THE DB EVEN THOUGH I ALREADY HAVE
//HAVE ALL THE DETAILS? I have not done it here.?????
ctx.Customers.Attach(entityCustomer);
ctx.ApplyCurrentValues(entityCustomer);
//Also Customer has addresses so
foreach(var address in entityCustomer.Addresses)
{
//some may be new addresses some might be modified one
?????? lost
}
}
else
{
///INSERT
ctx.Customers.AddObject(entityCustomer);
ctx.ObjectStateManager.ChangeObjectState(entityCustomer,EntityState.Added);
foreach(var address in entityCustomer.Addresses)
{
ctx.ObjectStateManager.ChangeObjectState(address ,EntityState.Added);
}
}
ctx.SaveChanges();
}
}