Exemplo n.º 1
0
        private void Save()
        {
            using (var context = new MasterDataContext())
            {
                if (!Validate(context))
                {
                    return;
                }

                var existingSupplier = context.Suppliers
                                       .Include(s => s.Contacts)
                                       .FirstOrDefault(s => s.Id == CurrentSupplier.Id);

                if (existingSupplier == null)
                {
                    context.Add(CurrentSupplier);
                }
                else
                {
                    context.Entry(existingSupplier).CurrentValues.SetValues(CurrentSupplier);
                    foreach (var contact in CurrentSupplier.Contacts)
                    {
                        var existingContact = existingSupplier.Contacts
                                              .FirstOrDefault(c => c.Id == contact.Id);

                        if (existingContact == null)
                        {
                            existingSupplier.Contacts.Add(contact);
                        }
                        else
                        {
                            context.Entry(existingContact).CurrentValues.SetValues(contact);
                        }
                    }

                    foreach (var contact in existingSupplier.Contacts)
                    {
                        if (!CurrentSupplier.Contacts.Any(c => c.Id == contact.Id))
                        {
                            context.Remove(contact);
                        }
                    }
                }

                context.SaveChanges();
                NotificationRequest.Raise(new Notification {
                    Content = "保存成功", Title = "提示"
                });
                IsEdit = true;
            }
        }