TOKYODRIFT!
TOKYODRIFT!
CC#
Created by TOKYODRIFT! on 6/21/2024 in #help
Is it possible to update public IReadOnlyList?
There is public IReadOnlyList<ISelectionNode> Selections { get; } from public api I know it is not a good idea but I want to extend it. Is it possible?
12 replies
CC#
Created by TOKYODRIFT! on 6/19/2024 in #help
✅ how to convert Dictionary to C# object?
I have Dictionary<string, object> map string is property name and object is property value is it possible to deserialize this to real object?
2 replies
CC#
Created by TOKYODRIFT! on 5/28/2024 in #help
The instance of entity type 'OptimizerInstanceEntity' cannot be tracked
Can someone help me to update model?
public sealed record OptimizerSettingsSetsEntity : OptimizerSettingsSets, IIdentityEntity
{
public new string Identity { get => base.Identity; init => base.Identity = value; }
public List<OptimizerInstanceEntity> OptimizerInstances { get; init; } = [];
public DateTime Created { get; init; }
public Guid Id { get; init; }
public DateTime Timestamp { get; init; }
public DateTime? Updated { get; init; }
}

public sealed record OptimizerInstanceEntity : IdentityEntity
{
public required string Url { get; set; }
}
public sealed record OptimizerSettingsSetsEntity : OptimizerSettingsSets, IIdentityEntity
{
public new string Identity { get => base.Identity; init => base.Identity = value; }
public List<OptimizerInstanceEntity> OptimizerInstances { get; init; } = [];
public DateTime Created { get; init; }
public Guid Id { get; init; }
public DateTime Timestamp { get; init; }
public DateTime? Updated { get; init; }
}

public sealed record OptimizerInstanceEntity : IdentityEntity
{
public required string Url { get; set; }
}
I want to create entity, add it to database and then update only instances My command doesn't work, I got exception after trying to update:
protected override async Task UpdateCoreAsync(OptimizerSettingsSetsModel model, EventHandlingContext context)
{
var exists = await FindByIdentityAsync(model.Identity, context);
if(exists == null)
return;

if(!ChangesComparer.HasChanges(exists.ToModel(), model))
return;

var entity = CreateEntity(model, exists);
var entry = dbContext.OptimizerSettingsSets.Update(entity);
await dbContext.SaveChangesAsync(context.CancellationToken);
entry.State = EntityState.Detached;
await eventDispatcher.OptimizerSettingsSetsUpdatedAsync(entity, context);
}
protected override async Task UpdateCoreAsync(OptimizerSettingsSetsModel model, EventHandlingContext context)
{
var exists = await FindByIdentityAsync(model.Identity, context);
if(exists == null)
return;

if(!ChangesComparer.HasChanges(exists.ToModel(), model))
return;

var entity = CreateEntity(model, exists);
var entry = dbContext.OptimizerSettingsSets.Update(entity);
await dbContext.SaveChangesAsync(context.CancellationToken);
entry.State = EntityState.Detached;
await eventDispatcher.OptimizerSettingsSetsUpdatedAsync(entity, context);
}
6 replies
CC#
Created by TOKYODRIFT! on 5/16/2024 in #help
✅ is it okay to use try/catch for logic behavior?
for example here, what is better and why
private string GetHost(string endpoint)
{
try
{
var myUri = new Uri(endpoint as string);
return myUri.Host;
}
catch
{
return endpoint;
}
}
private string GetHost(string endpoint)
{
try
{
var myUri = new Uri(endpoint as string);
return myUri.Host;
}
catch
{
return endpoint;
}
}
private string GetHost(string endpoint)
{
return Uri.TryCreate(endpoint, UriKind.Absolute, out var validUri)
? validUri.Host
: endpoint;
}
private string GetHost(string endpoint)
{
return Uri.TryCreate(endpoint, UriKind.Absolute, out var validUri)
? validUri.Host
: endpoint;
}
12 replies
CC#
Created by TOKYODRIFT! on 5/6/2024 in #help
✅ How to get all data without Include?
maybe stupid question but I want to ask it: I have two methods:
[UseProjection]
[Authorize(Roles = [Permissions.Rms.Task.Read])]
public Task<WorkingTaskWithFlights?> SingleWorkingTaskWithFlightAsync([Service(ServiceKind.Resolver)] ReadModelDbContext dbContext, IResolverContext context, string identity, [Service] NpgsqlHealthChecker npgsqlHealthChecker, CancellationToken cancellationToken)
=> HealthCheck(npgsqlHealthChecker, async () =>
{
var workingTask = await dbContext.WorkingTasks
.Include(workingTask => workingTask.RequiredQualifications)
.ThenInclude(workingTask => workingTask.Qualification)
.Include(workingTask => workingTask.StartLocation)
.Include(workingTask => workingTask.EndLocation)
.Include(workingTask => workingTask.WorkingShift)
.FirstOrDefaultAsync(workingTask => workingTask.Identity == identity, cancellationToken)
.ConfigureAwait(false);

if(workingTask == null)
return default;

var inboundIdentity = workingTask.CustomData?.InboundFlightLegIdentity;
var outboundIdentity = workingTask.CustomData?.OutboundFlightLegIdentity;

var flights = await dbContext.Flights
.Where(flight => flight.Identity == inboundIdentity || flight.Identity == outboundIdentity)
.ToListAsync(cancellationToken)
.ConfigureAwait(false);

return new WorkingTaskWithFlights { WorkingTask = workingTask, Flights = flights.AsReadOnly()};
});

[UseProjection]
[Authorize(Roles = [Permissions.Rms.Task.Read])]
public Task<WorkingTaskEntity?> SingleWorkingTaskAsync([Service(ServiceKind.Resolver)] ReadModelDbContext dbContext, IResolverContext context, string identity, [Service] NpgsqlHealthChecker npgsqlHealthChecker, CancellationToken cancellationToken)
=> GetByIdentityAsync(dbContext.WorkingTasks, identity, w => w.Project(context), npgsqlHealthChecker, cancellationToken);
[UseProjection]
[Authorize(Roles = [Permissions.Rms.Task.Read])]
public Task<WorkingTaskWithFlights?> SingleWorkingTaskWithFlightAsync([Service(ServiceKind.Resolver)] ReadModelDbContext dbContext, IResolverContext context, string identity, [Service] NpgsqlHealthChecker npgsqlHealthChecker, CancellationToken cancellationToken)
=> HealthCheck(npgsqlHealthChecker, async () =>
{
var workingTask = await dbContext.WorkingTasks
.Include(workingTask => workingTask.RequiredQualifications)
.ThenInclude(workingTask => workingTask.Qualification)
.Include(workingTask => workingTask.StartLocation)
.Include(workingTask => workingTask.EndLocation)
.Include(workingTask => workingTask.WorkingShift)
.FirstOrDefaultAsync(workingTask => workingTask.Identity == identity, cancellationToken)
.ConfigureAwait(false);

if(workingTask == null)
return default;

var inboundIdentity = workingTask.CustomData?.InboundFlightLegIdentity;
var outboundIdentity = workingTask.CustomData?.OutboundFlightLegIdentity;

var flights = await dbContext.Flights
.Where(flight => flight.Identity == inboundIdentity || flight.Identity == outboundIdentity)
.ToListAsync(cancellationToken)
.ConfigureAwait(false);

return new WorkingTaskWithFlights { WorkingTask = workingTask, Flights = flights.AsReadOnly()};
});

[UseProjection]
[Authorize(Roles = [Permissions.Rms.Task.Read])]
public Task<WorkingTaskEntity?> SingleWorkingTaskAsync([Service(ServiceKind.Resolver)] ReadModelDbContext dbContext, IResolverContext context, string identity, [Service] NpgsqlHealthChecker npgsqlHealthChecker, CancellationToken cancellationToken)
=> GetByIdentityAsync(dbContext.WorkingTasks, identity, w => w.Project(context), npgsqlHealthChecker, cancellationToken);
7 replies
CC#
Created by TOKYODRIFT! on 5/3/2024 in #help
✅ How to fill the object without populating properties?
I have this record:
public sealed record WorkingTaskWithFlights: WorkingTask
{
public List<Flight>? Flights { get; init; }
}
public sealed record WorkingTaskWithFlights: WorkingTask
{
public List<Flight>? Flights { get; init; }
}
and in my code:
var workingTask = dbContext.WorkingTasks.FirstOrDefault(...);
var flights = dbContext.Flights.Select(...);
var workingTask = dbContext.WorkingTasks.FirstOrDefault(...);
var flights = dbContext.Flights.Select(...);
workingTask is WorkingTask record and flights is Flight record, I need now somehow create a WorkingTaskWithFlights but without populating properties of workingTask
1 replies
CC#
Created by TOKYODRIFT! on 4/30/2024 in #help
✅ why dispose call is the latest in the chain?
Actually I have two questions here: 1. How actually duck typing works? Why I can do this:
using var refStruct = new RefStruct();
public ref struct RefStruct
{
public void Dispose()
{
Console.WriteLine("Hello from ref struct!");
}
}
using var refStruct = new RefStruct();
public ref struct RefStruct
{
public void Dispose()
{
Console.WriteLine("Hello from ref struct!");
}
}
but can't do the same with class, class requires to inherit IDisposable and it is strange:
using var simpleClass = new SimpleClass();
public class SimpleClass
{
public void Dispose()
{
Console.WriteLine("Hello from class!");
}
}
using var simpleClass = new SimpleClass();
public class SimpleClass
{
public void Dispose()
{
Console.WriteLine("Hello from class!");
}
}
2 question is: why dispose call is the latest in the chain? for example:
using var refStruct = new RefStruct();
using var simpleClass = new SimpleClass();
var factory = Factory.Create();
Console.WriteLine(factory);
using var refStruct = new RefStruct();
using var simpleClass = new SimpleClass();
var factory = Factory.Create();
Console.WriteLine(factory);
and output will be: Created Factory! Hello from class! Hello from ref struct!
11 replies
CC#
Created by TOKYODRIFT! on 4/26/2024 in #help
✅ how to merge two objects?
Sometimes ago I had this object:
public sealed record CreateFlightLegModel
{
public string? Identity { get; init; }
public LegIdentityArgument? LegIdentity { get; init; }
public JsonDocument? LegData { get; set; }
}
public sealed record CreateFlightLegModel
{
public string? Identity { get; init; }
public LegIdentityArgument? LegIdentity { get; init; }
public JsonDocument? LegData { get; set; }
}
LegData used in method for merging and for example we can do this: var firstLeg =
JsonDocument.Parse(@"{
""fuel"":
{
""fuel_invoice_1"": ""1"",
""fuel_invoice_2"": ""2"",
""fuel_invoice_3"": ""3""
}
}");
JsonDocument.Parse(@"{
""fuel"":
{
""fuel_invoice_1"": ""1"",
""fuel_invoice_2"": ""2"",
""fuel_invoice_3"": ""3""
}
}");
var secondLeg=
JsonDocument.Parse(@"{
""fuel"":
{
""fuel_invoice_2"": null,
""fuel_invoice_3"": null
}
}");
JsonDocument.Parse(@"{
""fuel"":
{
""fuel_invoice_2"": null,
""fuel_invoice_3"": null
}
}");
and the output will be:
{
""fuel"":
{
""fuel_invoice_1"": ""1"",
""fuel_invoice_2"": null,
""fuel_invoice_3"": null
}
}
{
""fuel"":
{
""fuel_invoice_1"": ""1"",
""fuel_invoice_2"": null,
""fuel_invoice_3"": null
}
}
then we decided move from JsonDocument to model and this merge doesn't work anymore in case I pasted earlier output will be:
""fuel"":
{
""fuel_invoice_1"": null,
""fuel_invoice_2"": null,
""fuel_invoice_3"": null
}
""fuel"":
{
""fuel_invoice_1"": null,
""fuel_invoice_2"": null,
""fuel_invoice_3"": null
}
can someone understand me what to do?
9 replies
CC#
Created by TOKYODRIFT! on 4/15/2024 in #help
how to add new property to json?
I have following code:
var schema = File.ReadAllText("legData.json");
var result = Parse(schema);

Console.WriteLine(result);

string Parse(string jsonSchema)
{
using var document = JsonDocument.Parse(jsonSchema);
var root = document.RootElement;

if(!root.TryGetProperty("properties", out _))
return "";

var properties = root.GetProperty("properties").EnumerateObject();
var property = properties.FirstOrDefault(prop => prop.Value.TryGetProperty("generateModelClassName", out _));
var propertyProperties = property.Value.GetProperty("properties");
var formatted = $$"""{"properties": {{propertyProperties}}}""";
return formatted;
}
var schema = File.ReadAllText("legData.json");
var result = Parse(schema);

Console.WriteLine(result);

string Parse(string jsonSchema)
{
using var document = JsonDocument.Parse(jsonSchema);
var root = document.RootElement;

if(!root.TryGetProperty("properties", out _))
return "";

var properties = root.GetProperty("properties").EnumerateObject();
var property = properties.FirstOrDefault(prop => prop.Value.TryGetProperty("generateModelClassName", out _));
var propertyProperties = property.Value.GetProperty("properties");
var formatted = $$"""{"properties": {{propertyProperties}}}""";
return formatted;
}
I need to add following property to each property in propertyProperties: "additionalProperties": true but I don't understand how to do it correctly
13 replies
CC#
Created by TOKYODRIFT! on 4/10/2024 in #help
System.AggregateException: 'Some services are not able to be constructed
I stuck with this problem and don't understand how to fix it: InvalidOperationException: Unable to resolve service for type 'BackForFront.Settings.FlightLegAggregatorSettings' while attempting to activate 'BackForFront.Services.FlightLegAggregator.FlightLegAggregatorApi'. api:
public FlightLegAggregatorApi(
HttpClientFactory httpClientFactory,
CommonSettings commonSettings,
FlightLegAggregatorSettings flightLegAggregatorOptions) :
base(httpClientFactory, commonSettings.ContextHeaderName!)
{
this.createFlightLegEndpoint = flightLegAggregatorOptions.FlightLegCreateUri ?? throw new ArgumentNullException(nameof(flightLegAggregatorOptions));
this.updateFlightLegEndpoint = flightLegAggregatorOptions.FlightLegUpdateUri ?? throw new ArgumentNullException(nameof(flightLegAggregatorOptions));
}
public FlightLegAggregatorApi(
HttpClientFactory httpClientFactory,
CommonSettings commonSettings,
FlightLegAggregatorSettings flightLegAggregatorOptions) :
base(httpClientFactory, commonSettings.ContextHeaderName!)
{
this.createFlightLegEndpoint = flightLegAggregatorOptions.FlightLegCreateUri ?? throw new ArgumentNullException(nameof(flightLegAggregatorOptions));
this.updateFlightLegEndpoint = flightLegAggregatorOptions.FlightLegUpdateUri ?? throw new ArgumentNullException(nameof(flightLegAggregatorOptions));
}
how I register it:
public static IServiceCollection RegisterFlightLegCreationServices(this IServiceCollection services, IConfiguration configuration)
{
BindSettings<FlightLegAggregatorSettings>(services, configuration, "FlightLegAggregator");
BindSettings<SolverManagerSettings>(services, configuration, "SolverManager");
BindSettings<DmnSettings>(services, configuration, "Dmn");
BindSettings<ReadModelClientSettings>(services, configuration, "ReadModelClient");

services.AddTransient<HttpClientFactory>();
services.AddTransient<FlightLegAggregatorApiBase, FlightLegAggregatorApi>();
services.AddScoped<FlightLegAggregatorServiceBase, FlightLegAggregatorService>();

return services;
}
public static IServiceCollection RegisterFlightLegCreationServices(this IServiceCollection services, IConfiguration configuration)
{
BindSettings<FlightLegAggregatorSettings>(services, configuration, "FlightLegAggregator");
BindSettings<SolverManagerSettings>(services, configuration, "SolverManager");
BindSettings<DmnSettings>(services, configuration, "Dmn");
BindSettings<ReadModelClientSettings>(services, configuration, "ReadModelClient");

services.AddTransient<HttpClientFactory>();
services.AddTransient<FlightLegAggregatorApiBase, FlightLegAggregatorApi>();
services.AddScoped<FlightLegAggregatorServiceBase, FlightLegAggregatorService>();

return services;
}
4 replies
CC#
Created by TOKYODRIFT! on 4/8/2024 in #help
✅ what should I do to use derived class for return type?
I have following:
public abstract class CommandResult
{
public string Error { get; set; }
}

public abstract class CommandResult2 : CommandResult
{
public string Error { get; set; }
public string Data { get; set; }
}

public abstract class SolverManagerPureCommand<TArgument>
{
protected abstract Task<CommandResult> ExecuteInternalCoreAsync(TArgument argument);
}

public sealed class BuildDataSetCommand : SolverManagerPureCommand<string>
{
protected override Task<CommandResult> ExecuteInternalCoreAsync(string argument)
{
throw new NotImplementedException();
}
}
public abstract class CommandResult
{
public string Error { get; set; }
}

public abstract class CommandResult2 : CommandResult
{
public string Error { get; set; }
public string Data { get; set; }
}

public abstract class SolverManagerPureCommand<TArgument>
{
protected abstract Task<CommandResult> ExecuteInternalCoreAsync(TArgument argument);
}

public sealed class BuildDataSetCommand : SolverManagerPureCommand<string>
{
protected override Task<CommandResult> ExecuteInternalCoreAsync(string argument)
{
throw new NotImplementedException();
}
}
is it possible to return this?
protected override Task<CommandResult2> ExecuteInternalCoreAsync(string argument)
protected override Task<CommandResult2> ExecuteInternalCoreAsync(string argument)
1 replies
CC#
Created by TOKYODRIFT! on 4/2/2024 in #help
✅ transaction in transaction issue
I have this error: The connection is already in a transaction and cannot participate in another transaction. My code:
public override async Task<OperationResult> AddOrUpdateWorkingTasksAsync(
IReadOnlyList<Infrastructure.Data.WorkingTask> workingTasks,
EventHandlingContext context)
{
var transaction = await BeginTransactionAsync(context).ConfigureAwait(false);
await using(transaction)
{
foreach(var workingTask in workingTasks)
{
var existTask = await FindAsync(workingTask.Id, context).ConfigureAwait(false);
if(existTask != null)
await UpdateAsync(workingTask, context).ConfigureAwait(false);
else
await AddAsync(workingTask, context).ConfigureAwait(false);
}
await eventDispatcher.WorkingTasksUpdatedAsync(workingTasks!, context).ConfigureAwait(false);
await transaction.CommitAsync(context.CancellationToken).ConfigureAwait(false);
}
return OperationResult.Success;
}
public override async Task<OperationResult> AddOrUpdateWorkingTasksAsync(
IReadOnlyList<Infrastructure.Data.WorkingTask> workingTasks,
EventHandlingContext context)
{
var transaction = await BeginTransactionAsync(context).ConfigureAwait(false);
await using(transaction)
{
foreach(var workingTask in workingTasks)
{
var existTask = await FindAsync(workingTask.Id, context).ConfigureAwait(false);
if(existTask != null)
await UpdateAsync(workingTask, context).ConfigureAwait(false);
else
await AddAsync(workingTask, context).ConfigureAwait(false);
}
await eventDispatcher.WorkingTasksUpdatedAsync(workingTasks!, context).ConfigureAwait(false);
await transaction.CommitAsync(context.CancellationToken).ConfigureAwait(false);
}
return OperationResult.Success;
}
public async Task AddAsync(TEntity entity, TContext context)
{
var transaction = await rootRepository.BeginTransactionAsync(context).ConfigureAwait(false);
await using(transaction)
{
await AddCoreAsync(entity, context).ConfigureAwait(false);
await transaction.CommitAsync(context.CancellationToken).ConfigureAwait(false);
}
}
public async Task AddAsync(TEntity entity, TContext context)
{
var transaction = await rootRepository.BeginTransactionAsync(context).ConfigureAwait(false);
await using(transaction)
{
await AddCoreAsync(entity, context).ConfigureAwait(false);
await transaction.CommitAsync(context.CancellationToken).ConfigureAwait(false);
}
}
should AddAsync contain a transaction?
4 replies
CC#
Created by TOKYODRIFT! on 3/28/2024 in #help
System.InvalidOperationException: The LINQ expression 'DbSet<WorkingTask>() .Where(w => new Work
I have following code:
[UsePaging]
[UseProjection]
[UseFiltering]
[UseSorting]
[Authorize(Roles = [Permissions.Rms.Task.Read])]
public IQueryable<WorkingTask> WorkingTasks([Service(ServiceKind.Resolver)] ReadModelDbContext dbContext, IResolverContext context, [Service] NpgsqlHealthChecker npgsqlHealthChecker)
{
var workingTasks = dbContext.WorkingTasks
.AsQueryable()
.Project(context)
.Filter(context)
.Sort(context)
.ToList(); // Force client-side evaluation

return workingTasks.AsQueryable();
}
[UsePaging]
[UseProjection]
[UseFiltering]
[UseSorting]
[Authorize(Roles = [Permissions.Rms.Task.Read])]
public IQueryable<WorkingTask> WorkingTasks([Service(ServiceKind.Resolver)] ReadModelDbContext dbContext, IResolverContext context, [Service] NpgsqlHealthChecker npgsqlHealthChecker)
{
var workingTasks = dbContext.WorkingTasks
.AsQueryable()
.Project(context)
.Filter(context)
.Sort(context)
.ToList(); // Force client-side evaluation

return workingTasks.AsQueryable();
}
I don't know why but I always get error after .Sort(context).ToList();. how to fix this?
11 replies
CC#
Created by TOKYODRIFT! on 3/25/2024 in #help
✅ how to check attribute name?
I have following:
if (syntaxNode
is RecordDeclarationSyntax
and MemberDeclarationSyntax { AttributeLists.Count: > 0 } member)
{
MemberSyntaxes.Add(member);
}
if (syntaxNode
is RecordDeclarationSyntax
and MemberDeclarationSyntax { AttributeLists.Count: > 0 } member)
{
MemberSyntaxes.Add(member);
}
I want to check if member contains special attribute. How to do it?
4 replies
CC#
Created by TOKYODRIFT! on 2/18/2024 in #help
How to create entity correctly? [EF CORE]
I have a following model:
public sealed record WorkingTask: BaseEntity
{
public required string Identity {get;set;}
public IReadOnlyList<RequiredQualifications>? RequiredQualifications { get; init; }
}
public sealed record WorkingTask: BaseEntity
{
public required string Identity {get;set;}
public IReadOnlyList<RequiredQualifications>? RequiredQualifications { get; init; }
}
public class RequiredQualifications
{
public string? QualificationId { get; set; }
public byte? Degree { get; set; }
}
public class RequiredQualifications
{
public string? QualificationId { get; set; }
public byte? Degree { get; set; }
}
how to store it correctly in database? should it be 1 - 1 or many-many? how to configure it in ef core? maybe I should add Id property to
RequiredQualifications
RequiredQualifications
? for example:
public class RequiredQualifications
{
public Guid WorkingTaskId {get;set;}
public string? QualificationId { get; set; }
public byte? Degree { get; set; }
}
public class RequiredQualifications
{
public Guid WorkingTaskId {get;set;}
public string? QualificationId { get; set; }
public byte? Degree { get; set; }
}
6 replies
CC#
Created by TOKYODRIFT! on 2/8/2024 in #help
✅ What is reason of null! here?
I have this property in entity model:
[Required]
[MinLength(1)]
[MaxLength(100)]
public string Identity { get; set; } = null!;
[Required]
[MinLength(1)]
[MaxLength(100)]
public string Identity { get; set; } = null!;
33 replies
CC#
Created by TOKYODRIFT! on 2/6/2024 in #help
Find doesn't return my collection
Shift contains a property: Qualifications I'm trying to add them to Shifts and it works! But when I get Shift using FindCoreAsync Qualifications in null
protected override async Task AddCoreAsync(Shift shift, EventHandlingContext context)
{
shift.Created = timeProvider.GetUtcNow().DateTime;
dbContext.Shifts.Add(shift);
dbContext.ShiftQualifications.AddRange(shift.Qualifications!);
await dbContext.SaveChangesAsync(context.CancellationToken).ConfigureAwait(false);
}

public override async Task<Shift?> FindCoreAsync(Shift shift, EventHandlingContext context)
{
var foundShift = await dbContext.Shifts
.AsNoTracking()
.FirstOrDefaultAsync(
s => s.ScheduledStart == shift.ScheduledStart
&& s.Type == shift.Type
&& s.ResourceId == shift.ResourceId,
context.CancellationToken)
.ConfigureAwait(false);

return foundShift;
}
protected override async Task AddCoreAsync(Shift shift, EventHandlingContext context)
{
shift.Created = timeProvider.GetUtcNow().DateTime;
dbContext.Shifts.Add(shift);
dbContext.ShiftQualifications.AddRange(shift.Qualifications!);
await dbContext.SaveChangesAsync(context.CancellationToken).ConfigureAwait(false);
}

public override async Task<Shift?> FindCoreAsync(Shift shift, EventHandlingContext context)
{
var foundShift = await dbContext.Shifts
.AsNoTracking()
.FirstOrDefaultAsync(
s => s.ScheduledStart == shift.ScheduledStart
&& s.Type == shift.Type
&& s.ResourceId == shift.ResourceId,
context.CancellationToken)
.ConfigureAwait(false);

return foundShift;
}
4 replies
CC#
Created by TOKYODRIFT! on 2/5/2024 in #help
✅ How to create migration correctly? What do I do wrong?
Command in Package Manager Console: PM> add-migration UpdateSomeModels -contex ReadModelDbContext Error:
Unable to create a 'DbContext' of type 'ReadModelDbContext'. The exception 'Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[ReadModel.Infrastructure.ReadModelDbContext]' while attempting to activate 'ReadModel.Infrastructure.ReadModelDbContext'.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
Unable to create a 'DbContext' of type 'ReadModelDbContext'. The exception 'Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[ReadModel.Infrastructure.ReadModelDbContext]' while attempting to activate 'ReadModel.Infrastructure.ReadModelDbContext'.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
public sealed class ReadModelDbContext: DbContext
{
public ReadModelDbContext(DbContextOptions<ReadModelDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Qualification>().HasAlternateKey(x => x.Identity);
modelBuilder.Entity<Function>().HasIndex(x => x.Name);
modelBuilder.Entity<Resource>().HasIndex(x => x.Identity);
modelBuilder.Entity<Node>().HasIndex(x => x.Identity);
modelBuilder.Entity<Location>().HasIndex(x => x.Identity);
modelBuilder.Entity<Shift>().HasAlternateKey(x => new { x.ScheduledStart, x.Type, x.ResourceId });
}

public DbSet<Qualification> Qualifications => Set<Qualification>();
public DbSet<Function> Functions => Set<Function>();
public DbSet<FunctionQualification> FunctionQualifications => Set<FunctionQualification>();
public DbSet<ResourceQualification> ResourceQualifications => Set<ResourceQualification>();
public DbSet<Resource> Resources => Set<Resource>();
public DbSet<Node> Nodes => Set<Node>();
public DbSet<Location> Locations => Set<Location>();
public DbSet<Edge> Edges => Set<Edge>();
public DbSet<ShiftQualification> ShiftQualifications => Set<ShiftQualification>();
public DbSet<Shift> Shifts => Set<Shift>();
}
public sealed class ReadModelDbContext: DbContext
{
public ReadModelDbContext(DbContextOptions<ReadModelDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Qualification>().HasAlternateKey(x => x.Identity);
modelBuilder.Entity<Function>().HasIndex(x => x.Name);
modelBuilder.Entity<Resource>().HasIndex(x => x.Identity);
modelBuilder.Entity<Node>().HasIndex(x => x.Identity);
modelBuilder.Entity<Location>().HasIndex(x => x.Identity);
modelBuilder.Entity<Shift>().HasAlternateKey(x => new { x.ScheduledStart, x.Type, x.ResourceId });
}

public DbSet<Qualification> Qualifications => Set<Qualification>();
public DbSet<Function> Functions => Set<Function>();
public DbSet<FunctionQualification> FunctionQualifications => Set<FunctionQualification>();
public DbSet<ResourceQualification> ResourceQualifications => Set<ResourceQualification>();
public DbSet<Resource> Resources => Set<Resource>();
public DbSet<Node> Nodes => Set<Node>();
public DbSet<Location> Locations => Set<Location>();
public DbSet<Edge> Edges => Set<Edge>();
public DbSet<ShiftQualification> ShiftQualifications => Set<ShiftQualification>();
public DbSet<Shift> Shifts => Set<Shift>();
}
12 replies
CC#
Created by TOKYODRIFT! on 2/1/2024 in #help
Is it worth to use AsNoTracking in dbset?
I found this:
public class ReadOnlyReadModelDbContext
{
readonly ReadModelDbContext dbContext;
public ReadOnlyReadModelDbContext(ReadModelDbContext dbContext)
{
this.dbContext = dbContext;
}
public IQueryable<Qualification> Qualifications => dbContext.Qualifications.AsNoTracking();
public IQueryable<Function> Functions => dbContext.Functions.AsNoTracking();
public IQueryable<FunctionQualification> FunctionQualifications => dbContext.FunctionQualifications.AsNoTracking();
public IQueryable<Resource> Resources => dbContext.Resources.AsNoTracking();
public IQueryable<Node> Nodes => dbContext.Nodes.AsNoTracking();
public IQueryable<Location> Locations => dbContext.Locations.AsNoTracking();
}
public class ReadOnlyReadModelDbContext
{
readonly ReadModelDbContext dbContext;
public ReadOnlyReadModelDbContext(ReadModelDbContext dbContext)
{
this.dbContext = dbContext;
}
public IQueryable<Qualification> Qualifications => dbContext.Qualifications.AsNoTracking();
public IQueryable<Function> Functions => dbContext.Functions.AsNoTracking();
public IQueryable<FunctionQualification> FunctionQualifications => dbContext.FunctionQualifications.AsNoTracking();
public IQueryable<Resource> Resources => dbContext.Resources.AsNoTracking();
public IQueryable<Node> Nodes => dbContext.Nodes.AsNoTracking();
public IQueryable<Location> Locations => dbContext.Locations.AsNoTracking();
}
In my opinion it doesn't look correct. What do you think?
10 replies
CC#
Created by TOKYODRIFT! on 2/1/2024 in #help
✅ How to use switch correctly?
I have following:
var rootRepositoryTest = pureCommand.BaseType?.GetGenericTypeDefinition() switch
{
var t when t == typeof(ReadModelPureCommand<>) => scope.ServiceProvider.GetService<ReadModelRootRepository<EventHandlingContext>>(),
var t when t == typeof(ResourceManagerPureCommand<>) => scope.ServiceProvider.GetService<ResourceManagerRootRepository<ExecutionEventHandlingContext>>(),
};
var rootRepositoryTest = pureCommand.BaseType?.GetGenericTypeDefinition() switch
{
var t when t == typeof(ReadModelPureCommand<>) => scope.ServiceProvider.GetService<ReadModelRootRepository<EventHandlingContext>>(),
var t when t == typeof(ResourceManagerPureCommand<>) => scope.ServiceProvider.GetService<ResourceManagerRootRepository<ExecutionEventHandlingContext>>(),
};

and I have error in switch: Cannot find best common type for types {ReadModelRootRepository<EventHandlingContext>?,ResourceManagerRootRepository<ExecutionEventHandlingContext>?} what should I do?
1 replies