通过 iCollection 模型在 WebAPI 中添加记录?
Add records in WebAPI via iCollection Model?
在 WebAPI POST 控制器中,使用 EntityFramework,我想添加一些基于 ICollection 的新记录。
所以,我有一个产品模型。此模型具有对模型颜色的引用 (ICollection)。
我有一个 POST 控制器,它应该能够添加一种或多种颜色,绑定到产品。
我有以下代码:
public async Task<IHttpActionResult> PostProduct(string InternalReferenceId, int SupplierId, Colors colors)
{
Product dbProduct = db.Products.FirstOrDefault(s => s.InternalReferenceId == InternalReferenceId && s.SupplierId == SupplierId);
if (dbProduct != null)
{
// iCollection
dbProduct.Colors = colors;
await db.SaveChangesAsync();
}
else
{
return NotFound();
}
return Ok();
}
JSON 可能看起来像这样;
{
"color": "white"
},
{
"color": "black"
},
{
"color": "green"
}
关于我如何将 dbProduct.Colors
分配给 content/model 颜色的任何想法,即 JSON?
您正在尝试将单个项目 (Models.Color
) 分配给集合 (ICollection<Models.Color>
)。因此,您需要更改 API 以接受 Models.Color
:
的集合
public async Task<IHttpActionResult> PostProduct(string InternalReferenceId, int SupplierId, ICollection<Color> colors)
在 WebAPI POST 控制器中,使用 EntityFramework,我想添加一些基于 ICollection 的新记录。
所以,我有一个产品模型。此模型具有对模型颜色的引用 (ICollection)。 我有一个 POST 控制器,它应该能够添加一种或多种颜色,绑定到产品。
我有以下代码:
public async Task<IHttpActionResult> PostProduct(string InternalReferenceId, int SupplierId, Colors colors)
{
Product dbProduct = db.Products.FirstOrDefault(s => s.InternalReferenceId == InternalReferenceId && s.SupplierId == SupplierId);
if (dbProduct != null)
{
// iCollection
dbProduct.Colors = colors;
await db.SaveChangesAsync();
}
else
{
return NotFound();
}
return Ok();
}
JSON 可能看起来像这样;
{
"color": "white"
},
{
"color": "black"
},
{
"color": "green"
}
关于我如何将 dbProduct.Colors
分配给 content/model 颜色的任何想法,即 JSON?
您正在尝试将单个项目 (Models.Color
) 分配给集合 (ICollection<Models.Color>
)。因此,您需要更改 API 以接受 Models.Color
:
public async Task<IHttpActionResult> PostProduct(string InternalReferenceId, int SupplierId, ICollection<Color> colors)