C
C#Marcoelho97

❔ I apparently have an infinite loop, but I can't fix it to work

I've tried a lot of stuff, even a "NewtonJson" fix I saw, but it wouldn't solve the problem because whenever I would get all my movies, it would not include the MoviesParticipantsSeasons part With the Newtonjson, it would let me get MoviesParticipantsSeason with the includes though What am I doing wrong? Do I really need NewtonJson? Please help, been on this for days now :/
J
Jimmacleβ€’401d ago
the problem is you have bidirectional navigation properties in your EF model which creates infinite cycles when you try to serialize it to JSON i would have separate models, one for your database and one for json serialization or for a quick and dirty solution, annotate the redundant properties so they're ignored by the json serializer
M
Marcoelho97β€’401d ago
How would that work, exactly? I would use this model I already have for database creation And then another for _context.xyz?
J
Jimmacleβ€’401d ago
you would define a new set of classes specifically to represent the data you want to serialize, then write a mapping function to convert your DB representation to that assuming you're returning this data as part of a web request you should really separate your database models and DTOs anyway for example, in one of my current projects i do things like this
public async Task<Result<ShippingOrderDetailsDto>> Handle(GetShippingOrderDetailsQuery request,
CancellationToken cancellationToken)
{
await using var db = await _db.CreateDbContextAsync(cancellationToken);
var order = await db.ShippingOrders.AsNoTracking()
.Include(o => o.RequestedBy)
.Where(o => o.Number == request.Number)
.Select(o => new ShippingOrderDetailsDto(
o.Number, o.RequestedBy.FullName, o.Description, o.Address, o.Method, o.CostCenter.Id + " " + o.CostCenter.Name, o.Packages,
o.CreatedOn, o.ShippedOn, o.TrackingNumber, o.CostUsd, o.Attn, o.ShipTo,
o.BillTo, o.Status, o.Project, o.Carrier, o.AccountNumber,
o.Packages.Sum(p => p.UnitValueUsd * p.Quantity)))
.FirstOrDefaultAsync(cancellationToken);
return order ?? Result<ShippingOrderDetailsDto>.Fail("Order not found.");
}
public async Task<Result<ShippingOrderDetailsDto>> Handle(GetShippingOrderDetailsQuery request,
CancellationToken cancellationToken)
{
await using var db = await _db.CreateDbContextAsync(cancellationToken);
var order = await db.ShippingOrders.AsNoTracking()
.Include(o => o.RequestedBy)
.Where(o => o.Number == request.Number)
.Select(o => new ShippingOrderDetailsDto(
o.Number, o.RequestedBy.FullName, o.Description, o.Address, o.Method, o.CostCenter.Id + " " + o.CostCenter.Name, o.Packages,
o.CreatedOn, o.ShippedOn, o.TrackingNumber, o.CostUsd, o.Attn, o.ShipTo,
o.BillTo, o.Status, o.Project, o.Carrier, o.AccountNumber,
o.Packages.Sum(p => p.UnitValueUsd * p.Quantity)))
.FirstOrDefaultAsync(cancellationToken);
return order ?? Result<ShippingOrderDetailsDto>.Fail("Order not found.");
}
ignore the ridiculous amount of properties
M
Marcoelho97β€’401d ago
So Your model is ShippingOrders Your return is the ShippingOrderDetailsDto, in which you select every property you wanna return? So that you can "remove" the unwanted ones?
J
Jimmacleβ€’401d ago
essentially correct
M
Marcoelho97β€’401d ago
That is genius
J
Jimmacleβ€’401d ago
i map the data in the database to an object that has the data the frontend needs it also means that if you ever need to change your database or API they aren't tightly coupled and you don't necessarily have to change them together
J
Jimmacleβ€’401d ago
the DTO is a very simple object that's easy to serialize and only has the exact data needed by the endpoint
M
Marcoelho97β€’401d ago
I'll give that a go :D Thank you so much!
J
Jimmacleβ€’401d ago
(i don't actually serialize to JSON because this is a blazor server app, but the concepts apply either way)
M
Marcoelho97β€’401d ago
But I still have a question, what about a create? How would I use a DTO and not the model? For example I create a movie Save I then create a relationship And when I go to save, it goes into loop too
J
Jimmacleβ€’401d ago
you'd do the same thing but backwards your client sends JSON that you deserialize into a DTO, then translate that into your DB model
M
Marcoelho97β€’401d ago
But the problem happens because of the DB Model, no? Because of that "Movie" and "MovieParticipantSeason" properties
J
Jimmacleβ€’401d ago
the exception you got is related to reading/writing JSON, not your DB model EF core will handle navigation properties automatically
M
Marcoelho97β€’401d ago
So, is it happening because I'm returning the object at its full? That makes sense πŸ€” I will give this a try and give feedback :D Thank you so much! It worked! Thank you so much! β™₯
A
Accordβ€’331d ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity. Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts
βœ… doing nothingdfg❔ I would appreciate some help.So i have this assignment and in lieu of my grandma who passed this past week i've not had the oppor❔ Discord Bot Service ProblemDoes anyone know how to register that service properly?❔ abstract class vs interface```cs public interface IFoo { protected static string GetFormattedTime() => DateTimeβœ… Refit / RestLess API SDK StructureHey! How do I structure an SDK for my API? Let's say I have 2 resources: Users and Groups. I coul❔ Best way to display a continually updating list of messages```cs @inject MerpieClient Client @inject MerpieHubConnection HubConnection @inject ILogger<MessageL❔ How can I fix this I keep getting null value in my string variable❔ How do I go from interface to implementation while navigating ASP.NET core code?I saw this youtube video and he seamlessly navigates the source? How can I do this? Thanks.Console Application published as PublishSingleFile the window auto close for few devloper.I have published a .exe file with runtime framework included, and distributed to other developer forβœ… Set Background color for one specific Row in GridI have a WPF project and a grid with a bunch of rows and columns. How can I change the background co❔ Facial recognition and centering using emgucv and arduino servos (visual studio)Hi guys, I am code illiterate. I found this code and need help because I do not know how to fix any ❔ Speech Recognizition makes me wanna cryI have already tried, using speech recogniztion on C++,Rust and now C#, since when this was that har❔ SystΓ¨me connexion wpfHello, Is someone making a connection system in wpf c# xaml to be simultaneously connected to my sitβœ… How to use SVGs in XAML file (WPF)I have a WPF project and I want to use an svg file in MainWindow.xaml. How do I properly use svg in ❔ Progress bar value from 0 to 100 over 3 seconds for my splash screenI CANNOT GET IT TO WORK❔ How are prices changes/updates commonly handled in e-commerce?Is polling/signalr used to display relevant/current prices? What about when the price changes during❔ Copying selected item from list box to another list box (Utilizing data source)I cant seem to be able to copy one item from a listbox to another, my current code I am attempting i❔ Im a begginerthe script just copies the text from running a command in cmd why does it work if i use systeminfo o❔ Widget for Windows using WFA c#Hello, how i can make a widget for Windows 10 using WFA c# it just a program without border? what is❔ I am learning and I do not know what is wrongI am following a brackeys tutorial and have only changed the text to be written.