Пример #1
0
        /// <inheritdoc />
        public async Task <string> DeleteContact(long id)
        {
            //Get contact object
            Contact contact = _context.Contact.Where(c => c.Id == id).FirstOrDefault();

            //delete if exist
            if (contact != null)
            {
                //Delete from contact table first
                contact = _context.Contact.Remove(contact).Entity;
                _context.SaveChanges();   //commit changes

                //Delete dependencies
                Name name = _context.Name.First(n => n.IName == contact.IName);
                _context.Name.Remove(name);

                Address address = _context.Address.First(a => a.IAddress == contact.IAddress);
                _context.Address.Remove(address);

                //Get the right Phone List object based on contact id (foreign key)
                List <Phone> phonelist = _context.Phone.Where(p => p.ContactId == contact.Id).ToList();
                foreach (Phone phone in phonelist)
                {
                    _context.Phone.Remove(phone);
                }

                await _context.SaveChangesAsync();    //commit changes

                return("Contact deleted");
            }
            else
            {
                return("Contact not found");
            }
        }
Пример #2
0
        private void SetUpClient()
        {
            ContactsAPI.Globals globals = new ContactsAPI.Globals();
            globals.ConnectionString = "DataSource=D:\\tfs\\web\\Contacts API\\ContactsAPI\\Contacts.db";

            var builder = new WebHostBuilder()
                          .UseStartup <ContactsAPI.Startup>()
                          .ConfigureServices(services =>
            {
                var context = new contactsContext(new DbContextOptionsBuilder <contactsContext>()
                                                  //.UseSqlite("DataSource=:memory:")
                                                  .UseSqlite("DataSource=D:\\tfs\\web\\Contacts API\\ContactsAPI\\Contacts.db")
                                                  .EnableSensitiveDataLogging()
                                                  .Options, globals);

                services.RemoveAll(typeof(contactsContext));
                services.AddSingleton(context);

                context.Database.OpenConnection();
                context.Database.EnsureCreated();

                context.SaveChanges();

                // Clear local context cache
                foreach (var entity in context.ChangeTracker.Entries().ToList())
                {
                    entity.State = EntityState.Detached;
                }
                repository = new Repository(context);
            });

            _server = new TestServer(builder);

            Client = _server.CreateClient();
        }