SWEETPONY
SWEETPONY
CC#
Created by SWEETPONY on 7/18/2024 in #help
✅ A problem with tracking behavior in unit tests
I have this error in unit tests:
The instance of entity type 'QualificationEntity' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
The instance of entity type 'QualificationEntity' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
Unit tests look like this:
[Test]
public Task AddAsync_AddWorkingTask_Success() =>
ExecuteTestCaseWithTestingContextAsync(async context => {
context.DbContext.Qualifications.Add(qualification);
context.DbContext.SaveChanges();

...

await context.WorkingTaskRepository.ScheduleWorkingTaskAsync(workingTask, eventContext);
});
[Test]
public Task AddAsync_AddWorkingTask_Success() =>
ExecuteTestCaseWithTestingContextAsync(async context => {
context.DbContext.Qualifications.Add(qualification);
context.DbContext.SaveChanges();

...

await context.WorkingTaskRepository.ScheduleWorkingTaskAsync(workingTask, eventContext);
});
protected async Task ExecuteTestCaseWithTestingContextAsync(Func<TestingContext, Task> asserter)
{
if(asserter == null)
Assert.Fail();
var options = CreateDbOptions();
using(var dbContext = new DbContext(options))
{
await dbContext.Database.EnsureDeletedAsync().ConfigureAwait(false);
await dbContext.Database.EnsureCreatedAsync().ConfigureAwait(false);
var testingContext = new TestingContext(dbContext);
await asserter.Invoke(testingContext).ConfigureAwait(false);
}
}
protected async Task ExecuteTestCaseWithTestingContextAsync(Func<TestingContext, Task> asserter)
{
if(asserter == null)
Assert.Fail();
var options = CreateDbOptions();
using(var dbContext = new DbContext(options))
{
await dbContext.Database.EnsureDeletedAsync().ConfigureAwait(false);
await dbContext.Database.EnsureCreatedAsync().ConfigureAwait(false);
var testingContext = new TestingContext(dbContext);
await asserter.Invoke(testingContext).ConfigureAwait(false);
}
}
everything will be ok if I remove context.DbContext.Qualifications.Add(qualification); but I don't want to
1 replies
CC#
Created by SWEETPONY on 7/16/2024 in #help
✅ is there any way to delete items from the database and return the deleted list in one request?
is there any way to delete items from the database and return the deleted list in one request? I can do something like this: DbContext.T.Where(entity => ..).ExecuteDelete(), but my business logic assumes that I will return items that were deleted I can do this: var deleted = DbContext.T.Where(entity => ..) DbContext.RemoveRange(deleted) but these are already two requests to database
14 replies
CC#
Created by SWEETPONY on 7/2/2024 in #help
✅ How to optimize this method?
I have this method:
protected override async Task UpdateCoreAsync(WorkingTaskModel workingTask, EventHandlingContext context)
{
var exist = await FindByIdentityAsync(workingTask.Identity, context).ConfigureAwait(false);
if(exist == null)
return;
if(await UpdateInternalAsync(workingTask, exist, context).ConfigureAwait(false))
{
var stateIsChanged = exist.State != workingTask.State;
if(stateIsChanged)
{
var historyModel = new WorkingTaskHistoryModel
{
ChangedData = new ChangedWorkingTaskModel(){State = workingTask.State},
UserIdentity = context.Context.UserAccountIdentity,
SourceName = context.Context.SourceName,
UpdatedAt = timeProvider.GetUtcNow().DateTime
};

await UpdateWorkingTaskHistoryAsync(historyModel, exist, context).ConfigureAwait(false);
}

var found = await FindByIdentityAsync(workingTask.Identity, context).ConfigureAwait(false);
await eventDispatcher.WorkingTaskUpdatedAsync(found!, exist, context).ConfigureAwait(false);
}
}
protected override async Task UpdateCoreAsync(WorkingTaskModel workingTask, EventHandlingContext context)
{
var exist = await FindByIdentityAsync(workingTask.Identity, context).ConfigureAwait(false);
if(exist == null)
return;
if(await UpdateInternalAsync(workingTask, exist, context).ConfigureAwait(false))
{
var stateIsChanged = exist.State != workingTask.State;
if(stateIsChanged)
{
var historyModel = new WorkingTaskHistoryModel
{
ChangedData = new ChangedWorkingTaskModel(){State = workingTask.State},
UserIdentity = context.Context.UserAccountIdentity,
SourceName = context.Context.SourceName,
UpdatedAt = timeProvider.GetUtcNow().DateTime
};

await UpdateWorkingTaskHistoryAsync(historyModel, exist, context).ConfigureAwait(false);
}

var found = await FindByIdentityAsync(workingTask.Identity, context).ConfigureAwait(false);
await eventDispatcher.WorkingTaskUpdatedAsync(found!, exist, context).ConfigureAwait(false);
}
}
the problem is: I need to call FindByIdentityAsync twice and we need this just to check updated property and send event. is it possible to remove second FindByIdentityAsync?
4 replies
CC#
Created by SWEETPONY 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 SWEETPONY 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 SWEETPONY 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 SWEETPONY 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 SWEETPONY 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 SWEETPONY 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 SWEETPONY 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 SWEETPONY 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 SWEETPONY 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 SWEETPONY 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 SWEETPONY 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 SWEETPONY 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 SWEETPONY 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 SWEETPONY 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 SWEETPONY 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 SWEETPONY 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 SWEETPONY 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