I am using .Net Core Entity Framework 3.1 for a web catalog application for automobile parts.
I have one simple controller, that returns all motorParts for a particular motor.
Here is that simple controller:
[HttpGet("GetPartsByMotorId/{id}")]
public async Task<ActionResult<IEnumerable<MotorParts>>> GetPartsByMotorId(Guid id)
{
var partsByMotor = await _context.MotorParts.Where(q => q.MotorId == id).OrderBy(c => c.partText).ToListAsync();
return partsByMotor;
}
It is returning the data, but it is in an order that I do not want and with some data duplicated.
The JSON looks like this when returned from the API:
[
{
"partId": "54",
"motorId": "3",
"partText": "Iron Heads",
"motor": {
"motorId": "3",
"motorText": "5.7 HEMI",
"motorParts": [
{
"partId": "54",
"motorId": "3",
"partText": "Iron Heads"
},
{
"partId": "8",
"motorId": "3",
"partText": "Aluminum Block"
}
]
}
},
{
"partId": "8",
"motorId": "3",
"partText": "Aluminum Block",
"motor": {
"motorId": "3",
"motorText": "5.7 HEMI",
"motorParts": [
{
"partId": "8",
"motorId": "3",
"partText": "Aluminum Block"
},
{
"partId": "54",
"motorId": "3",
"partText": "Iron Heads"
}
]
}
}
]
The problem for me, is that it is listing a "part" ( partId, motorId, partText ) first, then listing the same "parts" again later on.
But I want it to just list the motor data first, then all the parts for that motor, like this:
[
{
"motor": {
"motorId": "3",
"motorText": "5.7 HEMI",
"motorParts": [
{
"partId": "8",
"motorId": "3",
"partText": "Aluminum Block"
},
{
"partId": "54",
"motorId": "3",
"partText": "Iron Heads"
}
]
}
}
]
Here is the model:
public partial class MotorParts
{
public Guid PartId { get; set; }
public Guid? MotorId { get; set; }
public string PartText { get; set; }
public virtual MotorList Motor { get; set; }
}
And here is my database context for that model:
modelBuilder.Entity<MotorParts>(entity =>
{
entity.HasKey(e => e.PartId);
entity.HasOne(d => d.Motor)
.WithMany(p => p.MotorParts)
.HasForeignKey(d => d.MotorId)
.OnDelete(DeleteBehavior.Cascade)
.HasConstraintName("FK_carList_makeList");
entity.ToTable("MotorParts");
entity.Property(e => e.PartId)
.HasColumnName("PartId");
entity.Property(e => e.MotorId)
.HasColumnName("MotorId");
entity.Property(e => e.PartText)
.HasColumnName("PartText");
});
So I was wondering if there is a way to get the JSON format I want without changing my model too much. Is that possible?
Thanks!