public async Task <Inspection> UpdateAsync(Inspection inspection, CancellationToken cancellationToken = default) { if (inspection.Id == null) { return(null); } // Add or update related entities SpeciesEntity speciesEntity = DbContext.Species.Update(Mapper.Map <SpeciesEntity>(inspection.Species)).Entity; // Retrieve existing user entity and nesting box. Updating these this way is not supported. NestingBoxEntity nestingBoxEntity = await DbContext.NestingBoxes.FindAsync(new object[] { inspection.NestingBox.Id }, cancellationToken).ConfigureAwait(false); if (nestingBoxEntity == null) { return(null); } UserEntity inspectedByUserEntity = inspection.InspectedByUser != null ? await DbContext.Users.FindAsync(new object[] { inspection.InspectedByUser.Id }, cancellationToken).ConfigureAwait(false) : null; // Get existing inspection entity InspectionEntity inspectionEntity = await Entities.FindAsync(new object[] { inspection.Id }, cancellationToken).ConfigureAwait(false); if (inspectionEntity == null) { return(null); } // Update values inspectionEntity.NestingBox = nestingBoxEntity; inspectionEntity.InspectionDate = inspection.InspectionDate.GetValueOrDefault(); inspectionEntity.InspectedByUser = inspectedByUserEntity; inspectionEntity.HasBeenCleaned = inspection.HasBeenCleaned.GetValueOrDefault(); inspectionEntity.Condition = inspection.Condition.GetValueOrDefault(); inspectionEntity.JustRepaired = inspection.JustRepaired.GetValueOrDefault(); inspectionEntity.Occupied = inspection.Occupied.GetValueOrDefault(); inspectionEntity.ContainsEggs = inspection.ContainsEggs.GetValueOrDefault(); inspectionEntity.EggCount = inspection.EggCount; inspectionEntity.ChickCount = inspection.ChickCount.GetValueOrDefault(); inspectionEntity.RingedChickCount = inspection.RingedChickCount.GetValueOrDefault(); inspectionEntity.AgeInDays = inspection.AgeInDays; inspectionEntity.FemaleParentBirdDiscovery = inspection.FemaleParentBirdDiscovery.GetValueOrDefault(); inspectionEntity.MaleParentBirdDiscovery = inspection.MaleParentBirdDiscovery.GetValueOrDefault(); inspectionEntity.Species = speciesEntity; inspectionEntity.Comment = inspection.Comment; // Save changes await DbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return(Mapper.Map <Inspection>(inspectionEntity)); }
private static async Task ImportInspectionRecordAsync(NesteoDbContext dbContext, InspectionRecord inspectionRecord) { // Create collection for comments var comments = new List <string>(); if (!string.IsNullOrWhiteSpace(inspectionRecord.Comments)) { comments.AddRange(inspectionRecord.Comments.Split(',').Select(c => c.Trim()).Where(c => !string.IsNullOrEmpty(c))); } // Get nesting box entity NestingBoxEntity nestingBoxEntity = await dbContext.NestingBoxes.FindAsync(inspectionRecord.NestingBoxId).ConfigureAwait(false); if (nestingBoxEntity == null) { throw new InvalidCsvRecordException($"Nesting box {inspectionRecord.NestingBoxId} doesn't exist."); } // Ensure the species entity exists SpeciesEntity speciesEntity = null; if (!string.IsNullOrWhiteSpace(inspectionRecord.SpeciesName) && !new[] { "unbestimmt", "unbekannt" }.Contains(inspectionRecord.SpeciesName.ToLower())) { speciesEntity = await GetOrCreateEntityAsync(dbContext, species => species.Name == inspectionRecord.SpeciesName, () => new SpeciesEntity { Name = inspectionRecord.SpeciesName }).ConfigureAwait(false); } // Analyze date info DateTime inspectionDate = string.IsNullOrWhiteSpace(inspectionRecord.Date) ? throw new InvalidCsvRecordException("Inspection date not set.") : ParseDate(inspectionRecord.Date); // Map nesting box condition (Condition condition, bool justRepaired) = GetCondition(inspectionRecord.Condition); if (condition != Condition.Good) { comments.Add($"Kasten-Zustand: {inspectionRecord.Condition}"); } // Analyze ringing activity (ParentBirdDiscovery femaleParentBirdDiscovery, ParentBirdDiscovery maleParentBirdDiscovery, int ringedChickCount) = AnalyzeRingingActivity(inspectionRecord.RingedCount); // Create inspection dbContext.Inspections.Add(new InspectionEntity { NestingBox = nestingBoxEntity, InspectionDate = inspectionDate, InspectedByUser = null, HasBeenCleaned = GetYesNo(inspectionRecord.HasBeenCleaned), Condition = condition, JustRepaired = justRepaired, Occupied = GetYesNoWithUnknown(inspectionRecord.Occupied), ContainsEggs = !string.IsNullOrWhiteSpace(inspectionRecord.EggCount), EggCount = ParseNumberWithUnknown(inspectionRecord.EggCount), ChickCount = ParseNumberWithUnknown(inspectionRecord.ChickCount), RingedChickCount = ringedChickCount, AgeInDays = ParseNumberWithUnknown(inspectionRecord.ChickAges), FemaleParentBirdDiscovery = femaleParentBirdDiscovery, MaleParentBirdDiscovery = maleParentBirdDiscovery, Species = speciesEntity, ImageFileName = null, Comment = comments.Any() ? string.Join(", ", comments) : null, LastUpdated = inspectionDate }); }
public static async Task Main(string[] args) { // Create host IHost host = Server.Program.CreateHostBuilder(args).Build(); await Server.Program.PrepareHostAsync(host).ConfigureAwait(false); // Request database context var dbContext = host.Services.GetRequiredService <NesteoDbContext>(); // Safety check Console.Write("Do you want to fill the database with sample data? Please type 'yes': "); if (Console.ReadLine()?.ToLower() != "yes") { return; } Console.Write("Do you really want to do this? This will DELETE all existing data! Please type 'yes': "); if (Console.ReadLine()?.ToLower() != "yes") { return; } Console.WriteLine("Clearing database..."); // Clear database dbContext.Regions.RemoveRange(dbContext.Regions); dbContext.Owners.RemoveRange(dbContext.Owners); dbContext.Species.RemoveRange(dbContext.Species); dbContext.NestingBoxes.RemoveRange(dbContext.NestingBoxes); dbContext.ReservedIdSpaces.RemoveRange(dbContext.ReservedIdSpaces); dbContext.Inspections.RemoveRange(dbContext.Inspections); await dbContext.SaveChangesAsync().ConfigureAwait(false); Console.WriteLine("Generating sample data..."); var random = new Random(); UserEntity user = await dbContext.Users.AsQueryable().FirstOrDefaultAsync().ConfigureAwait(false); if (user == null) { Console.WriteLine("Please run the server first to make sure that at least one user exists."); return; } // Generate regions Console.WriteLine("Generating regions..."); await dbContext.Regions.AddRangeAsync( Enumerable.Range(1, 20).Select(i => new RegionEntity { Name = $"Region {i}", NestingBoxIdPrefix = ((char)('A' + (i - 1))).ToString() })) .ConfigureAwait(false); // Generate owners Console.WriteLine("Generating owners..."); await dbContext.Owners.AddRangeAsync(Enumerable.Range(1, 15).Select(i => new OwnerEntity { Name = $"Owner {i}" })).ConfigureAwait(false); // Generate species Console.WriteLine("Generating species..."); await dbContext.Species.AddRangeAsync(Enumerable.Range(1, 50).Select(i => new SpeciesEntity { Name = $"Species {i}" })).ConfigureAwait(false); // Generate nesting boxes Console.WriteLine("Generating nesting boxes..."); await dbContext.NestingBoxes.AddRangeAsync(Enumerable.Range(1, 400).Select(i => { RegionEntity region = dbContext.Regions.Local.GetRandomOrDefault(); return(new NestingBoxEntity { Id = $"{region.NestingBoxIdPrefix}{i:00000}", Region = region, OldId = random.Next(10) >= 5 ? "Old ID" : null, ForeignId = random.Next(10) >= 5 ? "Foreign ID" : null, CoordinateLongitude = 9.724372 + region.Id + (random.NextDouble() - 0.5) / 100, CoordinateLatitude = 52.353092 + (random.NextDouble() - 0.5) / 100, HangUpDate = DateTime.UtcNow.AddMonths(-6 - random.Next(24)), HangUpUser = user, Owner = dbContext.Owners.Local.GetRandomOrDefault(), Material = (Material)random.Next(4), HoleSize = (HoleSize)random.Next(7), ImageFileName = null, Comment = "This is a generated nesting box for testing purposes." }); })).ConfigureAwait(false); // Generate inspections Console.WriteLine("Generating inspections..."); await dbContext.Inspections.AddRangeAsync(Enumerable.Range(1, 2000).Select(i => { NestingBoxEntity nestingBox = dbContext.NestingBoxes.Local.GetRandomOrDefault(); return(new InspectionEntity { NestingBox = nestingBox, InspectionDate = nestingBox.HangUpDate.GetValueOrDefault().AddMonths(random.Next(6)), InspectedByUser = user, HasBeenCleaned = false, Condition = (Condition)random.Next(3), JustRepaired = false, Occupied = true, ContainsEggs = true, EggCount = random.Next(6), ChickCount = random.Next(1, 4), RingedChickCount = 1, AgeInDays = random.Next(6), FemaleParentBirdDiscovery = (ParentBirdDiscovery)random.Next(4), MaleParentBirdDiscovery = (ParentBirdDiscovery)random.Next(4), Species = dbContext.Species.Local.GetRandomOrDefault(), ImageFileName = null, Comment = "This is a generated inspection for testing purposes." }); })).ConfigureAwait(false); Console.WriteLine("Saving sample data..."); // Save changes await dbContext.SaveChangesAsync().ConfigureAwait(false); Console.WriteLine("Done."); }