I want to make an API that can receive any number of child IDs. and loop it in database adding 1 row for each child IDs. I tried making the CategoryChildId a list or array but it says Entity framework does not accept primitive types.
How can i achieve this?
for example when i receive a json like this:
"CategoryParentID": "4",
"CategoryChildID": [
{
5,6,7
}
],
It will store it in database like this.
I only have the code for adding single child at a time.
The service for the controller:
public async Task<ServiceResultWithoutBaseEntity<CategoryRollup>> Add(CategoryRollupViewModel newItem)
{
var result = new ServiceResultWithoutBaseEntity<CategoryRollup>();
result.Errors.AddRange(Validate(newItem));
if (result.HasErrors)
return result;
var item = newItem.MapToEntity(new CategoryRollup());
_context.CategoryRollups.Add(item);
await _context.SaveChangesAsync();
result.EntityResult = item;
return result;
}
model:
public class CategoryRollup
{
[Key]
public int ID { get; set; }
public int CategoryChildID { get; set; }
public int CategoryParentID { get; set; }
}
view model:
public class CategoryRollupViewModel
{
[Key]
public int ID { get; set; }
public int CategoryChildID { get; set; }
public int CategoryParentID { get; set; }
}
helper:
public static class CategoryRollupHelper
{
public static CategoryRollupViewModel MapFromEntity(this CategoryRollup source)
{
if (source == null)
return null;
var result = new CategoryRollupViewModel
{
CategoryChildID = source.CategoryChildID,
CategoryParentID = source.CategoryParentID,
};
return result;
}
public static CategoryRollup MapToEntity(this CategoryRollupViewModel source, CategoryRollup entity)
{
if (source == null || entity == null)
return null;
entity.CategoryChildID = source.CategoryChildID;
entity.CategoryParentID = source.CategoryParentID;
return entity;
}
}
