Need to structure JSON Array inside the Array group by its fields
I have the following structure of CS,
Goal Class:
public int Id { get; set; }
public string GoalName { get; set; }
public string CompanyName { get; set; }
//Navigation
public ICollection<Criteria> Criteria { get; set; }
and Criteria Class:
public int Id { get; set; }
public int Layer { get; set; }
public string CriteriaName { get; set; }
[ForeignKey(nameof(Goals))]
public int GoalId { get; set; }
public Goals Goals{ get; set; }
And Repository Class is written as:
public Goals GetGoalsById(int goalsId)
{
return FindByCondition(g => g.Id.Equals(goalsId))
.Include(crt=>crt.Criteria)..FirstOrDefault();;
API Structure is Look like:
{
"goalName": "Today Goal ",
"criteria": [
{
"layer": 1,
"criteriaName": "Cat 1"
},
{
"layer": 1,
"criteriaName": "Cat 2"
},
{
"layer": 1,
"criteriaName": "Cat 3"
},
{
"layer": 2,
"criteriaName": "C3"
},
{
"layer": 2,
"criteriaName": "C4"
},
{
"layer": 2,
"criteriaName": "C5"
}
],
}
But I want to JSON display group by layer like :
"goalName": "Today Goal ",
"criteria": [
"layer 1": [
{
"criteriaName": "Cat 1"
},
{
"criteriaName": "Cat 2"
},
{
"criteriaName": "Cat 3"
}
],
"layer 2": [
{
"criteriaName": "C3"
},
{
"criteriaName": "C4"
},
{
"criteriaName": "C5"
}
],
}
What would I do to achieve this kind JSON structure? The Layer is a int type fields in the criteria table, I need to display data with group by the layer so can call all the layer related data in a pair.
See also questions close to this topic
-
Read Serilog logs from MS-SQL (EntityFramework?)
What would you suggest for reading logs created by Serilog on a MS-SQL database? I am already using EF for the persistence layer in the project.
Should I add new models in the domain layer to represent the logs I want to read, and just use EF to read them? Or should I not add them to the EF db context and write individual DB queries? (Alternatively, I could write stored procedures and call those from code)
-
Cannot separate code when using DbContext
I always try to separate my code as much as possible. I'm fairly new to ASP.NET Core but the code principles and software design patterns are the same in all languages, however, when using entity-framework, there's something that bothers me, or that I don't know how to deal with.
In my application, I have users, which of course are created when registering. The users can add specific items to their inventory and request items to share from other users.
So I have a
SharingRequests
table, which has information such asUserBorrowerId
,UserLenderId
,InventoryItemId
etc.When I now want to create a sharing request and assign the user to it, I have to it all in the same context. For example, if I do this
MethodA: await using (var context = new DbContext()) { User user = context .Users .Where(u => u.Id == userId) .First(); } methodB(user);
MethodB: await using (var context = new DbContext()) { Item item = context .Items .Where(i => i.Id == itemId) .First(); SharingRequest sharingRequest = new SharingRequest(); sharingRequest.Item = item; sharingRequest.User = user; context.SharingRequests.AddAsync(sharingRequest); context.SaveChangesAsync(); }
I get the error that the user already exists in the database and it cannot create a new entry because of the duplicate key.
After googling this issue, I found that this is, because I have multiple database contexts, and the 2nd context doesn't know about the first one.
However, this means, that EVERY entity that I need, which needs to be loaded etc. all needs to IN ONE
await using (var context = new DbContext())
I fail to see how I can separate my code logically with this restriction. This forces me to have a method that does way too much things.
Why isn't it possible to have a method to get the user, another one to build the sharing request (another one to do the validation) etc.?
Am I missing sth. completely here? I can't imagine that this is the way applications have to be build because of the duplicate key problem.
-
Sort Main-List by property of Sublist in LINQ
Currently i have the following structure of my classes:
public class StoreElement { [Display(Name="ID")] public int StoreElementId { get; set; } [Display(Name = "RegalID")] public string StoreElementCode { get; set; } [Display(Name = "Regal")] public string Storage { get; set; } [Display(Name="Ebene")] public string Level { get; set; } [Display(Name = "Fach")] public string Shelf { get; set; } [Display(Name = "ESL Tag")] public string ESLTagId { get; set; } [Display(Name ="ESL Layout Template")] public string ESLLayoutValue { get; set; } [Display(Name = "Eingelagertes Material")] public List<Material> Materials { get; set; }
}
And this class:
public class Material { [Display(Name = "ID")] public int MaterialId { get; set; } [Display(Name = "Materialnummer")] public int? MaterialNumber { get; set; } [Display(Name = "Auftragsnummer")] public int? OrderNumber { get; set; } [Display(Name = "Eingelagert")] public bool? IsStored { get; set; } [Display(Name = "Einlagerdatum")] public DateTime StoredAt { get; set; } [Display(Name = "Auslagerdatum")] public DateTime OutsourcedAt { get; set; } [Display(Name = "Liefertermin")] public DateTime DeliveryDate { get; set; } [Display(Name = "Priorisiertes Material")] public bool PriorityMaterial { get; set; } public int? StoreElementId { get; set; } public StoreElement StoreElement { get; set; } }
A StoreElement can hold a List of Materials. The class Materials contains a property which is a date. Now i would like to order the Storage-Location List by the subproperty date of a list of materials.
I tried something in linq like that:
var myOrderdStorageLocationsByDeliveryDateOfMaterialsSublist = this.MyDatabaseContext.StorageLocations.Include(x=>x.Materials).OrderBy(x=>x.Materials.OrderBy(y=>y.DeliveryDate)).ToList();
But this throws an exception that says "Failed to compare two elements in the array"
-
Post Request to API not working | Angular 10.2
I'm trying to create a new Guest in my DB over a API I made myself. The API works fine with a C#-Front-end and Postman. Now I'm trying to use Angular for my front-end. I'm very new to Angular.
This is my Post-httpsRequest. Did a make a obvious mistake? I can't figure it out why it's not working. No Error appears in the console or Log in Browser.
save(guest: Guest) { return this.http.post<Guest>(this.REST_URL, guest) .pipe( retry(3), catchError(this.handleError) ); }
-
Oracle BPM Fault Recovery By java API
Any one have used java API to recover Oracle BPM fault? I'm using the following code to recover BPM faults the code is running successfully but no changes have been made on the instance fault, even the fault modified date didn't change, unlike clicking retry button on the fault itself using the em.
package oracle.bpm.example; import java.util.Hashtable; import java.util.List; import javax.naming.Context; import oracle.soa.management.facade.Fault; import oracle.soa.management.facade.FaultRecoveryActionTypeConstants; import oracle.soa.management.facade.Locator; import oracle.soa.management.facade.LocatorFactory; import oracle.soa.management.facade.bpmn.BPMNServiceEngine; import oracle.soa.management.util.FaultFilter; /** * Note: the classes in oracle.soa.management.facade.bpmn and subpackages are * not part of the public API and are provided as part of an as-is example * for use in solving data issues in the current release. This example * is provided only to illustrate an approach for batch recover of instances * and should be modified to meet environment specific requirments and * thoroughly tested, including removal of userid and passwords. */ public class BatchFaultRecovery { public BatchFaultRecovery() { } public static void main(String[] args) { Locator locator = getLocator("t3://mydev:7001/soa-infra", "username", "password"); doRecovery(locator,"FaultHandlingExample", "Client", "ServiceTask"); } public static void doRecovery(Locator locator, String compositeName, String componentName, String activityName) { try { BPMNServiceEngine svcEngine = (BPMNServiceEngine)locator.getServiceEngine(Locator.SE_BPMN); FaultFilter faultFilter = new FaultFilter(); faultFilter.setCompositeName(compositeName); faultFilter.setComponentName(componentName); recoverFaults(svcEngine, faultFilter,activityName); } catch (Exception e) { e.printStackTrace(); } } public static Locator getLocator(String url, String user, String password) { try { Hashtable jndiProps = new Hashtable(); jndiProps.put(Context.PROVIDER_URL,url); jndiProps.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory"); jndiProps.put(Context.SECURITY_PRINCIPAL, user); jndiProps.put(Context.SECURITY_CREDENTIALS, password); jndiProps.put("dedicated.connection", "true"); return LocatorFactory.createLocator(jndiProps); } catch(Exception e) { e.printStackTrace(); throw new RuntimeException("Error getting Locator",e); } } public static void recoverFaults(BPMNServiceEngine svcEngine, FaultFilter faultFilter, String activityName) { System.out.println("Get Recoverable Faults"); try { faultFilter.setRecoverable(true); //Get faults using defined filter List<Fault> recoverableFaults = svcEngine.getFaults(faultFilter); for (Fault fault : recoverableFaults) { System.out.println(">>>>>>>>>"); System.out.println("Composite :"+fault.getCompositeDN().getCompositeName()); System.out.println("Composite Instance:"+fault.getCompositeInstanceId()); System.out.println("Component :"+fault.getComponentName()); System.out.println("Component Instance:"+fault.getComponentInstanceId()); System.out.println("Reference :"+fault.getReferenceName()); System.out.println("Service :"+fault.getServiceName()); System.out.println("Label :"+fault.getLabel()); System.out.println("Fault Id :"+fault.getId()); System.out.println("Fault Name :"+fault.getName()); System.out.println("isRecoverable :"+fault.isRecoverable()); System.out.println("Message :"+fault.getMessage()); //Retry fault System.out.println("Start recovery ..."); svcEngine.recoverFault(fault,FaultRecoveryActionTypeConstants.ACTION_RETRY,null); System.out.println("Finish recovery"); System.out.println("<<<<<<<<<"); } } catch (Exception e) { e.printStackTrace(); } } }
can any one help me to trace or find a solution for this?
-
Publish a event on Facebook with Graph api gives error 100 sub 33. post no problems
I'm trying to publish a event to facebook. I got this working for normal post. I testing it with the Graph api explorer (v9.0). I not used to working with Facebook so it might be some user error here.
I do have a ID, still wrapping my head around if it's a groupid or page id. I find the documentation a bit hard to figure out. I can post message to this ID https://graph.facebook.com/xxxxxxxxxx/feed. I get a post id back in return
When I do a GET on xxxxxxxx/events It will return the events that are posted allready. So my quess is I do have correct rights on events.
I try to copy one of the existing events
{ "description": "Description of the event", "end_time": "2021-07-12T03:00:00+0200", "name": "Name of the event", "place": { "name": "" }, "start_time": "2021-07-11T20:00:00+0200" }
The JSON seems correct and I thought I have all parameters correctly. But posting this back to Facebook gives me
{ "error": { "message": "Unsupported post request. Object with ID 'xxxxxxxxxxxx' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api", "type": "GraphMethodException", "code": 100, "error_subcode": 33, "fbtrace_id": "Als3x_281vFeO2c14TcovDq" } }
I trying to wrap my head around this. Is it rights? Error code seems parameters. But I just can't see it anymore.
-
Add or update entity in EF Core
I have an entity with a recursive relationship like:
public class Message { [Key] public int MessageId { get; set; } public int? ReplyToMessageId { get; set; } public Message ReplyToMessage { get; set; } public ICollection<Message> ReplyMessages { get; set; } }
I need to have an add or update method to save the messages So i write following code:
public void AddOrUpdate(Message message) { if(Context.Messages.Any(m => m.MessageId == message.MessageId)) Context.Messages.Update(message); else Context.Messages.Add(message); Context.SaveChanges(); }
this method make an exception when I pass an existing message with a collection of new replied messages
I test
BulkMerge
method of theEntity Framework Extensions
library and it's work fine but I'm looking for a solution with ef core without any extention -
.net core 5 friendly default culture routing
I tried to add multi language feature to my asp.net-core project but there are some changes between .net 3.1 and 5.0 in RequestLocalization and i couldn't get what i want. I added Resource files for each language and I used Resource in my razor pages, its working but there is one unwanted default route bug and i want my routing to work friendly for default culture.
This is what i want,
For default culture (Turkish):
site.com/foo site.com/foo/bar site.com/foo/bar/5
For non-default culture (English):
site.com/en/foo site.com/en/foo/bar site.com/en/foo/bar/5
My other problem is; my route accepts site.com/foo/foo/bar as Turkish culture as well and its not friendly.
My Startup sample code below:
public void ConfigureServices(IServiceCollection services) { services.AddResponseCompression(); services.AddLocalization(opts => opts.ResourcesPath = "Resources"); services.Configure<RequestLocalizationOptions>(options => { var supportedCultures = new[] { new CultureInfo("tr-TR"), new CultureInfo("en") }; options.DefaultRequestCulture = new RequestCulture("tr"); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; options.RequestCultureProviders.Insert(0, new RouteDataRequestCultureProvider()); }); services.AddControllersWithViews(); services.AddRazorPages(); services.AddRouting(options => options.LowercaseUrls = true); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseResponseCompression(); if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); var supportedCultures = new string[] { "tr-TR", "en" }; app.UseRequestLocalization(options => options .AddSupportedCultures(supportedCultures) .AddSupportedUICultures(supportedCultures) .SetDefaultCulture("tr-TR") .RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(context => Task.FromResult(new ProviderCultureResult("tr-TR")))) ); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute(name: "culture-route", pattern: "{culture}/{controller=Home}/{action=Index}/{id?}"); endpoints.MapControllerRoute(name: "default", "{culture=tr}/{controller=Home}/{action=Index}/{id?}"); }); }
Razor Resource usage and culture change navs
Resource files
How can I solve this or what am I doing wrong?
-
accessing httpclient service from within another service in .net 5
I am adding a httpclient as a service (within ConfigureServices(IServiceCollection services)) as follows:
services.AddHttpClient<RequestsClient>(c => { c.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory"); }) .ConfigurePrimaryHttpMessageHandler(() => { return new HttpClientHandler() { UseDefaultCredentials = true }; });
the RequestsClient class is constructed as:
public RequestsClient (HttpClient client, IHttpContextAccessor hca, ILogger<RequestsClient > log, Configuration config)
to use the RequestsClient service in any class/component needing it i'm injecting it as:
[Inject] protected RequestsClient requestsClient { get; set; }
all this works great.
I'm now in need of creating a second service, lets call it "TimedService". How can I use my RequestsClient service from within my second service, TimedService?
injecting it like i do with components won't work as the RequestsClient always is null. is there a way to give TimedService service access to my RequestsClient service?
I'm sorry if this is a stupid question, I'm fairly new to this
-
Using automapper expression mapping of id class to string lead to translation error in EFCore
I use AutoMapper to translate between business logic objects (Blo) and data transfer objects (Dto). The blo-class contain an id that is a class wheras the dto contains a string for that id. To load objects out of a database an expression on blo-level is created and translated via AutoMapper to dto-level.
The classes are:
public class Blo { public Blo(BloId id) { this.Id = id; } public BloId Id { get; set; } } [Table("dtos")] public class Dto { [Column("id")] [Key] public string Id { get; set; } } public class BloId { private readonly string _value; public BloId(string value = null) { this._value = value ?? Guid.NewGuid().ToString(); } public static bool operator ==(BloId left, BloId right) { if (object.ReferenceEquals(left, right)) { return true; } if (left is null || right is null) { return false; } return left._value == right._value; } public static bool operator !=(BloId left, BloId right) { return !(left == right); } public override string ToString() { return this._value; } }
These classes are very simplyfied and all the unneeded code is omitted due to focus on the real problem.
The mapping I created is straight forward (using the hints of that github issue):
cfg.CreateMap<Blo, Dto>(MemberList.None) .EqualityComparison((src, dst) => src.Id.ToString() == dst.Id) .ForMember(dst => dst.Id, opt => opt.MapFrom(src => src.Id.ToString())); cfg.CreateMap<Dto, Blo>(MemberList.None) .EqualityComparison((src, dst) => src.Id == dst.Id.ToString()) .ForMember(dst => dst.Id, opt => opt.MapFrom(src => new BloId(src.Id)));
I created a
DbContext
from EFCore and the following code to find an item:var mapper = CreateMapper(); await using (var ctx = new MyContext()) { var idToFind = new BloId("Container-Id 000"); Expression<Func<Blo, bool>> bloFilter = c => c.Id == idToFind; var dtoFilter = mapper.MapExpression<Expression<Func<Dto, bool>>>(bloFilter); var found = await ctx.Dtos.FirstOrDefaultAsync(dtoFilter); }
This works as expected if I use an in-memory database. But if I switch to e.g. a SQLite database the following exception occurs:
The LINQ expression 'DbSet<Dto> .Where(d => new BloId(d.Id) == Container-Id 000)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
And the reason is absolutally clear: The
bloFilter
isc => (c.Id == value(AutoMapperVsEfCore.Program+<>c__DisplayClass0_0).idToFind)
that is translated to the
dtoFilter
c => (new BloId(c.Id) == Container-Id 000)
That is the problem! There is no way to create an instance of
BloId
in SQL.The expected dto-filter might be something like:
c => (c.Id == "Container-Id 000")
But I've absolutally no idea how I have to configure AutoMapper to translate my specified blo-filter to a working dto-filter.
How do I create such a filter?
For completeness the used
DbContext
is:public class MyContext : DbContext { public const string DatabasePath = @"D:\Temp\testing.db"; public DbSet<Dto> Dtos { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //optionsBuilder.UseInMemoryDatabase("testing"); optionsBuilder.UseSqlite(new SqliteConnectionStringBuilder { DataSource = DatabasePath }.ToString()); base.OnConfiguring(optionsBuilder); } }
-
EF Core - Multiple references to the same table
Using Entity Framework Core (5.0.1) code first I'm having trouble implementing a class that has two references to another class.
This is basically the structure I want:
public class Location { public int Id { get; set; } public string Name { get; set; } } public class Race { public int Id { get; set; } public string Title { get; set; } public int? StartLocationId { get; set; } public Location StartLocation { get; set; } public int? EndLocationId { get; set; } public Location EndLocation { get; set; } }
This actually works fine, but as I'm implementing the form to create a new Race I want to add some validation attributes:
public class Race { public int Id { get; set; } [Required] public string Title { get; set; } [Required] public int? StartLocationId { get; set; } public Location StartLocation { get; set; } [Required] public int? EndLocationId { get; set; } public Location EndLocation { get; set; } }
The Required attributes on the location references makes it impossible to create the tables in the initialization of the database (which I'm currently running at all startups since I'm at the beginning of the development). This is the error message I get:
Introducing FOREIGN KEY constraint 'FK_Races_Locations_StartLocationId' on table 'Races' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint or index.
As I understand it this has to do with a problem with cascade delete. I'm ok with disabling cascade delete in the database, but I would like the properties to be required for validation in the GUI. Is that even possible?
For the other relations in my model classes that are not standard I use the Fluent Api to configure, so a solution using that would be best. However, solving the problem is my priority so a solution using attributes is also fine.
I have found other threads here on StackOverflow with very similiar questions, but none of the suggested solutions have worked for me (some are for Entity Framework, not Core):
EF Core Multiple References to Same Entity EF Core 2.2 - Two foreign keys to same table Entity Framework Code First - two Foreign Keys from same table Entity Framework multiple references to same table