开发者

How do I save Parent -Child using EntityFramework 4?

I am using EF4 and I have a situation where I need to insert a parent child into the database using sql server 2008. When Saving a customer I would like to save their addresses as well.

I have as follows:

public class Customer
{
  public string Name { get; set; }
  public string Surname{ get; set; }
  public List<Address> AddressList { get; set; }
}

public class Address
{
  public string StreetName { get; set; }
  public string  City { get; set; }
}

public in开发者_开发技巧t SaveCustomer(CustomerDto customer)
{
   //TODO NEED TO BE MODIFIED
        using (var ctx = new MyContext())
        {

           var entityCustomer = customer.ToEntityCustomer();

           var state = entityCustomer.CustomerID > 0 ? State.Modified : State.Added;

           ctx.Customers.Attach(entityCustomer);

           ctx.ObjectStateManager.ChangeObjectState(entityCustomer , EFStateUtil.GetState(state));

           var result = ctx.SaveChanges();
           return result;
        }
    }

How do I modify my code to save both the customer and addresses at the same time. Will it be one trip to the server?

Any suggestions?


You would have to do it for each and every Address object as well:

using (var ctx = new MyContext()) {
    var entityCustomer = customer.ToEntityCustomer();
    var state = entityCollectionGroup.CollectionGroupID > 0 
        ? State.Modified : State.Added;
    ctx.Customers.Attach(entityCustomer);
    ctx.ObjectStateManager.ChangeObjectState(entityCustomer, 
            EFStateUtil.GetState(state));

    foreach(address in entityCustomer.AddressList) {
        var addressState = // Your logic to figure out the state...
        ctx.ObjectStateManager.ChangeObjectState(address, addressState);    
    }

    var result = ctx.SaveChanges();
    return result;
}

And yes it's going to be only one trip to the database to save them all as per calling SaveChanges (Unit Of Work Pattern)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜