I am trying to pass my array to SQL Server, but I can only get a NULL value, and if I am trying to add a table row and pass it, I only receive 1 row in the database.
Here is the console log when I pass the array to SQL
This is where I post my array to SQL:
postButton(data) {
return this.http.post(environment.baseURL 'PropertyTransactionDetails/Add', data)
}
Here's my model:
public class PropertyTransactionDetailsDTO
{
public int Id { get; set; }
public string PropertyNumber { get; set; }
public string PropertyDescription { get; set; }
public string DeliveryReceiptNumber { get; set; }
}
This is my repository:
public async Task<PropertyTransactionDetailsDTO> Insert(PropertyTransactionDetailsDTO item)
{
PROPERTYTRANSACTIONDETAILS data = MapToEntity(item);
_ctx.Entry(data).State = EntityState.Added;
await _ctx.SaveChangesAsync();
return item;
}
And my controller:
[HttpPost("Add")]
public async Task<ActionResult<PropertyTransactionDetailsDTO>> Add([FromBody] PropertyTransactionDetailsDTO item)
{
if (item == null)
item = new PropertyTransactionDetailsDTO();
return Ok(await _PropertyTransactionDetailsRepository.Insert(item));
}
CodePudding user response:
By the looks of the code you shared you are sending an Array to the backend, however the backend expects an single object.
One way of solving this from the frontend would be (assuming data is indeed an Array and that you're subscribing to the result of pushButton):
function pushButton(data){
let tasks: Observable<any>[] = [];
data.ItemRec.forEach((item, index) => {
tasks.push(this.http.post(environment.baseURL 'PropertyTransactionDetails/Add', item))
});
return concat(...tasks)
}
If you have types defined in your Angular project then you can change any to that type.
Hope this helps.
minimal working example: https://stackblitz.com/edit/typescript-dspi9k?file=index.ts
Following the discussion the smallest step forward would be changing the onSave() function into:
onSave(){
console.log("onSave():",this.receivedPropertyForm.value);
this.receivedPropertyForm.value.ItemRec.forEach(prop=>{
this.micro.pushButton(prop).subscribe({next:(res)=>{console.log("After storing record:",res) } })
});
}
In the value property you have an ItemRec Array. With forEach() you will address each property in that array and send it to the database. Note that this is not the desired endstate, however it will work. Have a look at RxJS: https://rxjs.dev/guide/overview