我想要创建一个API,它可以接收任意数量的子ID。并在数据库中循环它,为每个子ID添加1行。我试着让CategoryChildId成为一个列表或数组,但它说实体框架不接受基本类型。
我怎样才能做到这一点?
例如,当我收到这样的json时:
"CategoryParentID": "4",
"CategoryChildID": [
{
5,6,7
}
],它会像这样存储在数据库中。

我只有一次添加独生子女的代码。
控制器的服务:
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;
}模型:
public class CategoryRollup
{
[Key]
public int ID { get; set; }
public int CategoryChildID { get; set; }
public int CategoryParentID { get; set; }
}视图模型:
public class CategoryRollupViewModel
{
[Key]
public int ID { get; set; }
public int CategoryChildID { get; set; }
public int CategoryParentID { get; set; }
}帮手:
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;
}
}发布于 2019-06-09 13:04:22
你需要了解EF ORM是如何工作的。
会重新设计你的模块。
让我们说你有
public class CategoryRollup
{
[Key]
public int ID { get; set; }
// Now i assume that CategoryChildID refer to a list of CategoryRollup as children
// then just make it so. you may have to config this in moduleBuilder
public List<CategoryRollup> CategoryChildren { get; set; }
/// and this is the parent
public CategoryRollup CategoryParent { get; set; }
}现在你的模型可以像这样,它的upp对你来说
public class CategoryRollupViewModel
{
public CategoryRollupViewModel(CategoryRollup item){
ID = item.ID;
CategoryChildID = item.CategoryChildren.Select(x=> x.ID).ToList();
CategoryParentID = item.CategoryParent?.ID;
}
[Key]
public int ID { get; set; }
public List<int> CategoryChildID { get; set; }
public int CategoryParentID { get; set; }
}我明白你的意思了吗?
https://stackoverflow.com/questions/56514622
复制相似问题