~π’πͺπ»π²πΎπΌ~
Entity Framework Entity Saving
Is maybe anything wrong with doing this? (setting it to new list?)
public sealed class Visitor : Entity<Guid>
{
public ICollection<PlannedVisit> PlannedVisits { get; set; } = new List<PlannedVisit>();
}
27 replies
Entity Framework Entity Saving
just creates the plannedVisit and adds it to the NavigationProperty "PlannedVisits"
public Result<PlannedVisit> PlanVisit(DateTime plannedArrival, DateTime? plannedDeparture, VisitLocation location, List<BriefingType> requiredBriefings, VisitGroup group)
{
var result = PlannedVisit.Create(
this,
plannedArrival,
plannedDeparture,
location,
group,
requiredBriefings);
if (result.Failed)
{
return result.Error;
}
PlannedVisits.Add(result.Value);
return result.Value;
}
27 replies
Entity Framework Entity Saving
Seems like EF Core tries to update the entity instead of inserting it?
UPDATE [visitor].[PlannedVisits] SET [Location] = @p0, [PlannedArrival] = @p1, [PlannedDeparture] = @p2, [RequiredBriefings] = @p3, [State] = @p4, [VisitId] = @p5, [VisitorId] = @p6, [GroupHeadCount] = @p7, [Group_Names] = @p8
OUTPUT 1
WHERE [Id] = @p9;
27 replies
Entity Framework Entity Saving
services.AddDbContext<IVisitorDbContext, VisitorDbContext>((services, options) =>
{
DatabaseSettings databaseSettings = services.GetRequiredService<IOptions<DatabaseSettings>>().Value;
options.UseSqlServer(databaseSettings.VisitorModuleConnectionString,
e => e.MigrationsAssembly(Assembly.GetExecutingAssembly().GetName().Name));
options.AddInterceptors(services.GetServices<ISaveChangesInterceptor>());
});
27 replies
Entity Framework Entity Saving
internal sealed class PlanVisitCommandHandler : ICommandHandler<PlanVisitCommand, PlannedVisitDto>
{
private readonly IVisitorDbContext _context;
public PlanVisitCommandHandler(IVisitorDbContext context)
{
_context = context;
}
public async Task<Result<PlannedVisitDto>> Handle(PlanVisitCommand request, CancellationToken cancellationToken)
{
Visitor? visitor = await _context.Visitors.FirstOrDefaultAsync(visitor => visitor.Id == request.VisitorId, cancellationToken);
if (visitor is null)
{
return VisitorErrors.VisitorNotFound;
}
var result = visitor.PlanVisit(
request.PlannedArrival,
request.PlannedDeparture,
request.Location,
request.RequiredBriefings.ToList());
if (result.Failed)
{
return result.Error;
}
await _context.SaveChangesAsync(cancellationToken);
return PlannedVisitDto.From(result.Value);
}
}
27 replies
Entity Framework Entity Saving
Mb
Error
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: "The database operation was expected to affect 1 row(s), but actually affected 0 row(s); data may have been modified or deleted since entities were loaded. See https://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions."
27 replies