public async Task <int> Handle(CreatePersistedURLCommand request, CancellationToken cancellationToken) { User?user = null; if (request?.UserId != null) { user = await _ctx.Users.FindAsync(request.UserId); if (user == null) { throw new BadRequestException("The specified user is unknown."); } } var shortURL = await GetShortURL(request?.DesiredShortURL); var persistedURL = new PersistedURL { URL = request.URL, // request cannot be null, but I still get a warning for that it might be :( ShortURL = shortURL, User = user }; await _ctx.PersistedURLs.AddAsync(persistedURL); await _ctx.SaveChangesAsync(cancellationToken); return(persistedURL.Id); }
private async Task SeedPersistedURLs(CancellationToken cancellationToken) { if (_ctx.PersistedURLs.Any()) { return; } var users = await _ctx.Users.ToDictionaryAsync(x => x.Id, x => x); var entities = SeedData.PersistedURLs(); AttachDbUsersToEntities(entities, users); await _ctx.PersistedURLs.AddRangeAsync(entities); await _ctx.SaveChangesAsync(cancellationToken); }