public void AddToGroups(Machine model, CancellationToken ct) { var groups = GroupNames.GetGroupNames(model); foreach (var group in groups) { var existingGroup = this._context.Groups.Include(o => o.GroupMachines).FirstOrDefaultAsync(o => o.Name.Equals(group), ct).Result; if (existingGroup != null && existingGroup.Name == group) { if (!existingGroup.GroupMachines.Any(o => o.MachineId.Equals(model.Id))) { existingGroup.GroupMachines.Add(new GroupMachine { GroupId = existingGroup.Id, MachineId = model.Id }); this._context.SaveChanges(); } } else { var newGroup = new Group(); newGroup.Name = group; newGroup.Status = StatusType.Active; newGroup.GroupMachines.Add(new GroupMachine { GroupId = newGroup.Id, MachineId = model.Id }); this._context.Groups.Add(newGroup); this._context.SaveChanges(); } } }